python网络爬虫


一、Python爬虫核心库

  1. HTTP请求库

    • requests:简单易用的HTTP请求库,处理GET/POST请求。
    • aiohttp:异步HTTP客户端,适合高并发场景。
  2. HTML/XML解析库

    • BeautifulSoup :基于DOM树的解析库,支持多种解析器(如lxml)。
    • lxml:高性能解析库,支持XPath语法。
  3. 动态页面处理

    • Selenium:模拟浏览器操作,处理JavaScript渲染的页面。
    • Playwright(推荐):新一代自动化工具,支持多浏览器。
  4. 数据存储

    • pandas:数据清洗与导出(CSV/Excel)。
    • SQLAlchemy:数据库ORM工具(如MySQL、PostgreSQL)。
  5. 框架

    • Scrapy:高性能爬虫框架,支持分布式、中间件、管道等特性。

二、爬虫开发步骤

1. 发起HTTP请求
python 复制代码
import requests

url = "https://example.com"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

response = requests.get(url, headers=headers)
if response.status_code == 200:
    html = response.text  # 或 response.content
2. 解析HTML内容

使用BeautifulSoup:

python 复制代码
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "lxml")
titles = soup.find_all("h1", class_="title")
for title in titles:
    print(title.text.strip())

使用XPath(配合lxml):

python 复制代码
from lxml import etree

tree = etree.HTML(html)
items = tree.xpath('//div[@class="item"]/a/@href')
3. 处理动态页面(Selenium示例)
python 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://example.com")
dynamic_content = driver.find_element(By.CSS_SELECTOR, ".dynamic-element").text
driver.quit()
4. 存储数据

保存到CSV:

python 复制代码
import csv

with open("data.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["标题", "链接"])
    writer.writerow(["Example", "https://example.com"])

保存到数据库(SQLAlchemy):

python 复制代码
from sqlalchemy import create_engine, Column, String
from sqlalchemy.orm import declarative_base

Base = declarative_base()
class Article(Base):
    __tablename__ = "articles"
    title = Column(String(200), primary_key=True)
    url = Column(String(200))

engine = create_engine("sqlite:///data.db")
Base.metadata.create_all(engine)

# 插入数据
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
session.add(Article(title="Example", url="https://example.com"))
session.commit()

三、实战示例:爬取豆瓣电影Top250

python 复制代码
import requests
from bs4 import BeautifulSoup
import csv

url = "https://movie.douban.com/top250"
headers = {"User-Agent": "Mozilla/5.0"}

def get_movies():
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, "lxml")
    movies = []
    for item in soup.find_all("div", class_="item"):
        title = item.find("span", class_="title").text
        rating = item.find("span", class_="rating_num").text
        movies.append((title, rating))
    return movies

def save_to_csv(movies):
    with open("douban_top250.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["电影名称", "评分"])
        writer.writerows(movies)

if __name__ == "__main__":
    movies = get_movies()
    save_to_csv(movies)

四、反爬虫策略与应对

  1. 常见反爬手段

    • User-Agent检测 :伪装浏览器头(如使用fake_useragent库)。
    • IP封禁 :使用代理IP池(如requests + proxies参数)。
    • 验证码:接入打码平台(如超级鹰)或OCR识别。
    • 频率限制 :设置随机请求间隔(如time.sleep(random.uniform(1,3)))。
  2. 推荐工具

    • 代理IP:快代理、芝麻代理。
    • 分布式爬虫:Scrapy + Redis(去重与任务队列)。

五、法律与道德规范

  1. 遵守robots.txt :检查目标网站的爬虫协议。
    • 访问 https://example.com/robots.txt
  2. 控制请求频率:避免对服务器造成压力。
  3. 数据用途:禁止商用或侵犯隐私。

六、进阶学习方向

  1. Scrapy框架:学习中间件、Item Pipeline、分布式爬虫。
  2. 动态渲染:掌握Selenium/Playwright自动化。
  3. 数据清洗 :使用pandas处理复杂数据。
  4. 反爬破解:逆向JavaScript加密参数(如AST解析)。

相关推荐
蓝莓味柯基4 小时前
Python 学习路线与笔记跳转(持续更新笔记链接)
笔记·python·学习
先鱼鲨生4 小时前
【Qt】初识Qt
开发语言·qt
唤醒手腕5 小时前
2025 年如何使用 Pycharm、Vscode 进行树莓派 Respberry Pi Pico 编程开发详细教程(更新中)
ide·python·pycharm
reasonsummer5 小时前
【办公类-99-04】20250504闵豆统计表excle转PDF,合并PDF、添加中文字体页眉+边框下划线
python·pdf·deepseek
chao_7895 小时前
QT开发工具对比:Qt Creator、Qt Designer、Qt Design Studio
开发语言·qt
CHNMSCS5 小时前
PyTorch_张量基本运算
人工智能·pytorch·python
时而支楞时而摆烂的小刘5 小时前
CUDA、pytorch、配置环境教程合集
人工智能·pytorch·python
Gui林6 小时前
【ROS2】launch启动文件如何集成到ROS2(Python版本)
linux·python
奋进的小暄6 小时前
数据结构(4) 堆
java·数据结构·c++·python·算法
珊瑚里的鱼6 小时前
LeetCode 102题解 | 二叉树的层序遍历
开发语言·c++·笔记·算法·leetcode·职场和发展·stl