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

相关推荐
浩瀚之水_csdn11 分钟前
Python 3 网络编程详解:从原理到实战
开发语言·网络·python
满怀冰雪13 分钟前
24_中间件系统源码分析_Middleware链的洋葱模型与异常处理
人工智能·python·中间件·langchain
江华森15 分钟前
03-python-包与模块异常处理
python
AI行业学习21 分钟前
2026 版 Notepad++ 完整图文安装指南|官方渠道无捆绑,一键切换中文界面
开发语言·人工智能·python·html·notepad++
炘东59228 分钟前
求助:在另一个 Reasonix 窗口或后台运行
python
apcipot_rain33 分钟前
计科八股2026705——正态分布、独立与不相关、范数、列表元组集合、链表队列、sort函数、URL执行
python·计算机网络·概率论
江华森40 分钟前
Python 编程快速上手:让繁琐工作自动化 —— 19章全实战笔记
笔记·python·自动化
子豪-中国机器人1 小时前
第一部分:初赛选择题(30 题,对应线上每日问答)
python
Sam09271 小时前
【AI 算法精讲 15】余弦相似度:向量检索与归一化内积
人工智能·python·算法·ai
Starry-sky(jing)1 小时前
RecursionError: maximum recursion depth exceeded —— 你的函数调用链,踩穿了 CPython 的安全气囊
python·cpython·pydantic·recursionerror·递归深度·递归限制·sys.setrecursionlimit