当前位置: 首页 > news >正文

Python 爬虫开发

文章目录

  • 1. 常用库安装
  • 2. 基础爬虫开发
    • 2.1. 使用 requests 获取网页内容
    • 2.2. 使用 BeautifulSoup 解析 HTML
    • 2.3. 处理登录与会话
  • 3. 进阶爬虫开发
    • 3.1. 处理动态加载内容(Selenium)
    • 3.2. 使用Scrapy框架
    • 3.3. 分布式爬虫(Scrapy-Redis)
  • 4. 爬虫优化与反反爬策略
    • 4.1. 常见反爬机制及应对
    • 4.2. 代理IP使用示例
    • 4.3. 随机延迟与请求头

BeautifulSoup 官方文档
https://beautifulsoup.readthedocs.io/zh-cn/v4.4.0/
https://cloud.tencent.com/developer/article/1193258
https://blog.csdn.net/zcs2312852665/article/details/144804553

参考:
https://blog.51cto.com/haiyongblog/13806452

1. 常用库安装

pip install requests beautifulsoup4 scrapy selenium pandas

2. 基础爬虫开发

2.1. 使用 requests 获取网页内容

import requestsurl = 'https://top.baidu.com/board?tab=realtime'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}response = requests.get(url, headers=headers)
print(response.status_code)     # 200表示成功
print(response.text[:500])      # 打印前500个字符

在这里插入图片描述

2.2. 使用 BeautifulSoup 解析 HTML

from bs4 import BeautifulSouphtml_doc = """<html><head><title>测试页面</title></head><body><p class="title"><b>示例网站</b></p><p class="story">这是一个示例页面<a href="http://example.com/1" class="link" id="link1">链接1</a><a href="http://example.com/2" class="link" id="link2">链接2</a></p>"""soup = BeautifulSoup(html_doc, 'html.parser')# 获取标题
print(soup.title.string)# 获取所有链接
for link in soup.find_all('a'):print(link.get('href'), link.string)# 通过CSS类查找
print(soup.find('p', class_='title').text)

2.3. 处理登录与会话

import requestslogin_url = 'https://example.com/login'
target_url = 'https://example.com/dashboard'session = requests.Session()# 登录请求
login_data = {'username': 'your_username','password': 'your_password'
}response = session.post(login_url, data=login_data)if response.status_code == 200:# 访问需要登录的页面dashboard = session.get(target_url)print(dashboard.text)
else:print('登录失败')

3. 进阶爬虫开发

3.1. 处理动态加载内容(Selenium)

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager# 设置无头浏览器
options = webdriver.ChromeOptions()
options.add_argument('--headless')  # 无界面模式
options.add_argument('--disable-gpu')# 自动下载chromedriver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)url = 'https://dynamic-website.com'
driver.get(url)# 等待元素加载(隐式等待)
driver.implicitly_wait(10)# 获取动态内容
dynamic_content = driver.find_element(By.CLASS_NAME, 'dynamic-content')
print(dynamic_content.text)driver.quit()

3.2. 使用Scrapy框架

# 创建Scrapy项目
# scrapy startproject example_project
# cd example_project
# scrapy genspider example example.com# 示例spider代码
import scrapyclass ExampleSpider(scrapy.Spider):name = 'example'allowed_domains = ['example.com']start_urls = ['http://example.com/']def parse(self, response):# 提取数据title = response.css('title::text').get()links = response.css('a::attr(href)').getall()yield {'title': title,'links': links}# 运行爬虫
# scrapy crawl example -o output.json

3.3. 分布式爬虫(Scrapy-Redis)

# settings.py配置
SCHEDULER = "scrapy_redis.scheduler.Scheduler"
DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter"
REDIS_URL = 'redis://localhost:6379'# spider代码
from scrapy_redis.spiders import RedisSpiderclass MyDistributedSpider(RedisSpider):name = 'distributed_spider'redis_key = 'spider:start_urls'def parse(self, response):# 解析逻辑pass

4. 爬虫优化与反反爬策略

4.1. 常见反爬机制及应对

User-Agent检测 :随机切换User-Agent
IP限制:使用代理IP池
验证码:OCR识别或打码平台
行为分析:模拟人类操作间隔
JavaScript渲染:使用Selenium或Pyppeteer

4.2. 代理IP使用示例

import requestsproxies = {'http': 'http://proxy_ip:port','https': 'https://proxy_ip:port'
}try:response = requests.get('https://example.com', proxies=proxies, timeout=5)print(response.text)
except Exception as e:print(f'请求失败: {e}')

4.3. 随机延迟与请求头

import random
import time
import requests
from fake_useragent import UserAgentua = UserAgent()def random_delay():time.sleep(random.uniform(0.5, 2.5))def get_with_random_headers(url):headers = {'User-Agent': ua.random,'Accept-Language': 'en-US,en;q=0.5','Referer': 'https://www.google.com/'}random_delay()return requests.get(url, headers=headers)

相关文章:

  • YOLO 算法详解:实时目标检测的里程碑
  • Java 树形结构,根据名称搜索
  • 知识宇宙-职业篇:软件测试工程师
  • 【VASP】PBE与HSE之前的区别
  • moviepy视频添加中文水印
  • [yolov11改进系列]基于yolov11替换卷积神经网CNN为KANConv的python源码+训练源码
  • 谷歌Veo vs Sora:AI视频生成技术的巅峰对决
  • 【Unity3D】将自动生成的脚本包含到C#工程文件中
  • 前端安全直传MinIO方案
  • Spring Cloud Gateway 限流实践:基于 Redis 令牌桶算法的网关层流量治理
  • Visual Studio 调试中 PDB 与图像不匹配
  • springcloud---gateway
  • [攻防世界] easyphp writeup
  • 北京大学肖臻老师《区块链技术与应用》公开课:02-BTC-密码学原理
  • 【React】- React-RND 深度使用指南:实现自由拖拽、避坑受控陷阱!
  • Java—— 多线程 第一期
  • cursor/vscode连接低版本的系统(glibc<2.28)
  • IntelliJ IDEA Ultimate修改软件地区使用
  • JavaSE核心知识点04工具04-02(IDEA)
  • 鸿蒙桌面快捷方式开发
  • 做移动网站建设/免费制作网站的软件
  • 网站 app 共同架构/百度一下浏览器下载安装
  • 徐州网站制作流程/东莞网站建设推广品众
  • wordpress 网站运行时间/长沙官网seo服务
  • 个人网站设计论文范文/百度网盟
  • 北京上海网站建设公司/图们网络推广