python爬虫如何写,有哪些成功爬取的案例

编写Python爬虫时,常用的库包括Requests、Beautiful Soup和Scrapy。以下是三个简单的Python爬虫案例,分别使用Requests和Beautiful Soup,以及Scrapy。

1. 使用Requests和Beautiful Soup爬取网页内容:

python 复制代码
import requests
from bs4 import BeautifulSoup

url = "https://example.com"
response = requests.get(url)

if response.status_code == 200:
    soup = BeautifulSoup(response.text, 'html.parser')
    # 在这里可以使用Beautiful Soup提取页面内容
    # 例如:titles = soup.find_all('h2')
    print(soup.title.text)
else:
    print(f"Failed to retrieve the page. Status code: {response.status_code}")

2. 使用Requests和正则表达式爬取图片:

python 复制代码
import requests
import re
from urllib.parse import urljoin

url = "https://example.com"
response = requests.get(url)

if response.status_code == 200:
    image_urls = re.findall(r'<img.*?src=["\'](.*?)["\']', response.text)
    for img_url in image_urls:
        full_url = urljoin(url, img_url)
        # 在这里可以下载图片或进行其他处理
        # 例如:response = requests.get(full_url); save_image(response.content, "image.jpg")
        print(full_url)
else:
    print(f"Failed to retrieve the page. Status code: {response.status_code}")

3. 使用Scrapy爬取网站:

首先,确保已安装Scrapy:

bash 复制代码
pip install scrapy

创建一个新的Scrapy项目:

bash 复制代码
scrapy startproject myproject
cd myproject

编辑Spider:

python 复制代码
# myproject/spiders/myspider.py
import scrapy

class MySpider(scrapy.Spider):
    name = 'myspider'
    start_urls = ['https://example.com']

    def parse(self, response):
        # 在这里可以使用XPath或CSS选择器提取数据
        # 例如:titles = response.xpath('//h2/text()').getall()
        title = response.css('title::text').get()
        print(title)

运行Scrapy爬虫:

bash 复制代码
scrapy crawl myspider

这些例子只是入门,实际项目中可能需要处理更多的异常情况、使用代理、设置请求头等。爬取网页时,请确保遵守网站的Robots.txt文件和使用者协议。

相关推荐
FYKJ_20101 分钟前
springboot高考志愿填报推荐系统14332-计算机课程设计、毕业设计
javascript·spring boot·python·架构·django·课程设计·高考
卷无止境4 分钟前
长篇写作 Skill 横向盘点:从单文件指令到多智能体流水线
后端·python
外收内放10 分钟前
FastAPI猜字谜实战(8):收官
开发语言·python·学习·fastapi
沉下心来学鲁班19 分钟前
具身智能实战:让机器鸭爬梯子——双策略交接与接触力控制的深度解读
开发语言·人工智能·python·机器人
TickDB22 分钟前
美股历史数据下载:用 Codex 取数,Python 导出 CSV
python·websocket·mcp·行情数据 api
云南新人和数采集团24 分钟前
开源项目吐槽大会:一篇技术文章的大纲设计
python·scrapy·开源
fengyangaiGEO26 分钟前
外贸B2B GEO优化:为何是平台成功的关键?
大数据·人工智能·python
小小张说故事39 分钟前
Python 的列表和元组到底差在哪?拆开 PyListObject 和 PyTupleObject,为什么一个能改一个不能
python