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文件和使用者协议。

相关推荐
Katecat996638 分钟前
【铁路检测】YOLO11-C3k2-StripCGLU模型在铁路轨道缺陷检测中的应用与改进
python
理想是做全栈工程师10 分钟前
基于UNet的带噪黑白数字图像分割模型
人工智能·pytorch·python·anaconda
lbb 小魔仙18 分钟前
从零搭建 Spring Cloud 微服务项目:注册中心 + 网关 + 配置中心全流程
java·python·spring cloud·微服务
霖雨22 分钟前
备份 SQL Server 到 Azure Storage
后端·python·microsoft·flask·azure
tjjucheng23 分钟前
小程序定制开发哪家有团队支持
python
我送炭你添花23 分钟前
Pelco KBD300A 模拟器:08.模板库 + 一键场景加载
运维·开发语言·python·自动化
weixin_4624462325 分钟前
JupyterLab 禁用 Terminal 的三种方法(安装记录,仅供参考)
python·jupyter·jupyterlab
飞Link25 分钟前
数据增强中的数据标注、数据重构、协同标注和非LLM驱动的增强
python·重构·数据挖掘
惜.己27 分钟前
使用python复制目录以及目录的子目录的文件到脚本运行的目录(工具+源码)
python