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

相关推荐
TechWayfarer4 小时前
查询IP所在地的3种方案:从API到离线库,风控场景怎么选?
开发语言·网络·python·网络协议·tcp/ip
程序员榴莲4 小时前
Python 单例模式
开发语言·python·单例模式
hh.h.5 小时前
昇腾CANN ops-transformer 仓的 MC2 算子:MoE 模型的全到全通信
python·深度学习·transformer·cann
NiceCloud喜云6 小时前
Claude Files API 深入:从上传、复用到配额管理的工程化指南
android·java·数据库·人工智能·python·json·飞书
专注VB编程开发20年6 小时前
windows下python自带标准库 ≈ 70% 纯.py 源码,30% .pyd(DLL)
python
萌新小码农‍7 小时前
人工智能数学基础+python实例(人工智能学习day3)
开发语言·人工智能·python
毋语天8 小时前
FastAPI 进阶实战:请求体、文件上传、响应模型与数据校验
python·fastapi·api开发·数据校验·pydantic
ZhengEnCi9 小时前
09a-斯坦福 CS336 作业一:BPE 分词器
python·神经网络
测试员周周9 小时前
【Appium 系列】第18节-重试与容错 — 移动端测试的稳定性保障
人工智能·python·功能测试·ui·单元测试·appium·测试用例