[Python] 超详细 Python 爬虫指南

577 0
Honkers 2025-3-5 16:43:32 | 显示全部楼层 |阅读模式

目录

一、爬虫的基本原理

二、爬虫实现步骤

1. 准备工作

2. 详细代码实现

三、处理反爬机制

四、爬取复杂数据的技巧

1. JSON 数据爬取

2. 分页数据爬取

3. 下载文件

五、完整爬虫示例

六、注意事项


一、爬虫的基本原理

  1. HTTP 请求与响应

    • 爬虫通过 HTTP 协议与目标网站服务器通信。
    • 发送请求时可指定 URL、请求方法(GET 或 POST)、请求头等。
    • 服务器根据请求返回 HTML 页面、JSON 数据或其他格式的响应。
  2. HTML 解析
    HTML 是网页的主要结构。爬虫通过解析 HTML 提取有用信息,如标题、图片、表格等。

  3. 数据存储
    抓取的数据可存储到文件(如 CSV、JSON)、数据库(如 MySQL、MongoDB)等介质中,便于后续分析。

  4. 反爬机制

    • User-Agent 检测:服务器检查请求来源是否合法。
    • 频率限制:高频访问可能触发封禁。
    • 验证码验证:部分网站通过验证码阻止自动化行为。
  5. robots.txt 协议
    网站通过 robots.txt 指定哪些页面可以被爬取,爬虫需遵守此协议。


二、爬虫实现步骤

1. 准备工作

安装必要的库:

  1. pip install requests beautifulsoup4 lxml pandas
复制代码
2. 详细代码实现

(1)发送 HTTP 请求 通过 requests 库获取网页内容。

  1. import requests
  2. # 定义目标 URL
  3. url = "https://example.com"
  4. # 设置请求头,伪装为浏览器访问
  5. headers = {
  6. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
  7. }
  8. # 发送请求
  9. response = requests.get(url, headers=headers)
  10. # 检查状态码
  11. if response.status_code == 200:
  12. print("请求成功!")
  13. print(response.text[:500]) # 打印部分网页内容
  14. else:
  15. print(f"请求失败,状态码: {response.status_code}")
复制代码

(2)解析 HTML 数据 使用 BeautifulSoup 提取 HTML 中的内容。

  1. from bs4 import BeautifulSoup
  2. # 使用 BeautifulSoup 解析 HTML
  3. soup = BeautifulSoup(response.text, "lxml")
  4. # 提取网页标题
  5. title = soup.title.string
  6. print(f"网页标题: {title}")
  7. # 提取所有超链接
  8. links = []
  9. for a_tag in soup.find_all("a", href=True):
  10. links.append(a_tag["href"])
  11. print("提取到的链接:")
  12. print("\n".join(links))
复制代码

(3)存储数据 将数据保存为 CSV 文件。

  1. import pandas as pd
  2. # 构造数据字典
  3. data = {"Links": links}
  4. # 转换为 DataFrame
  5. df = pd.DataFrame(data)
  6. # 保存为 CSV
  7. df.to_csv("links.csv", index=False, encoding="utf-8-sig")
  8. print("数据已保存到 links.csv")
复制代码

(4)动态网页处理 有些网页通过 JavaScript 加载数据,requests 无法直接抓取。这时需使用浏览器自动化工具,如 Selenium 或 Playwright。

以下是 Selenium 的示例:

  1. pip install selenium
复制代码
  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By
  3. # 配置 Selenium WebDriver(以 Chrome 为例)
  4. options = webdriver.ChromeOptions()
  5. options.add_argument("--headless") # 无头模式
  6. driver = webdriver.Chrome(options=options)
  7. # 打开网页
  8. driver.get("https://example.com")
  9. # 等待页面加载
  10. driver.implicitly_wait(10)
  11. # 提取动态加载的内容
  12. titles = driver.find_elements(By.TAG_NAME, "h1")
  13. for title in titles:
  14. print(title.text)
  15. # 关闭浏览器
  16. driver.quit()
复制代码

三、处理反爬机制

添加随机延迟 避免频繁请求被封禁:

  1. import time
  2. import random
  3. time.sleep(random.uniform(1, 3)) # 随机延迟 1-3 秒
复制代码

使用代理 IP 通过代理绕过 IP 封禁:

  1. proxies = {
  2. "http": "http://username:password@proxyserver:port",
  3. "https": "http://username:password@proxyserver:port"
  4. }
  5. response = requests.get(url, headers=headers, proxies=proxies)
复制代码

处理验证码 使用 OCR 识别验证码:

  1. pip install pytesseract pillow
复制代码
  1. from PIL import Image
  2. import pytesseract
  3. # 读取验证码图片
  4. image = Image.open("captcha.png")
  5. # 使用 OCR 识别文本
  6. captcha_text = pytesseract.image_to_string(image)
  7. print(f"验证码内容: {captcha_text}")
复制代码

 


 

四、爬取复杂数据的技巧

1. JSON 数据爬取

许多网站的动态内容通过 API 提供 JSON 数据,可以直接请求这些接口:

  1. api_url = "https://example.com/api/data"
  2. response = requests.get(api_url, headers=headers)
  3. # 解析 JSON 数据
  4. data = response.json()
  5. print(data)
复制代码
2. 分页数据爬取

自动抓取多页内容:

  1. base_url = "https://example.com/page={}"
  2. for page in range(1, 6):
  3. url = base_url.format(page)
  4. response = requests.get(url, headers=headers)
  5. print(f"抓取第 {page} 页内容")
复制代码
3. 下载文件

下载图片或文件到本地:

  1. file_url = "https://example.com/image.jpg"
  2. response = requests.get(file_url, stream=True)
  3. # 保存到本地
  4. with open("image.jpg", "wb") as file:
  5. for chunk in response.iter_content(chunk_size=1024):
  6. file.write(chunk)
  7. print("文件下载完成!")
复制代码

五、完整爬虫示例

以下是一个完整的爬虫脚本,抓取新闻网站标题与链接并保存为 CSV 文件:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import pandas as pd
  4. import time
  5. import random
  6. # 设置目标 URL 和请求头
  7. base_url = "https://news.ycombinator.com/"
  8. headers = {
  9. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
  10. }
  11. # 存储数据
  12. titles = []
  13. links = []
  14. # 爬取内容
  15. for page in range(1, 4): # 抓取前三页
  16. url = f"{base_url}?p={page}"
  17. response = requests.get(url, headers=headers)
  18. soup = BeautifulSoup(response.text, "lxml")
  19. for item in soup.find_all("a", class_="titlelink"):
  20. titles.append(item.text)
  21. links.append(item["href"])
  22. print(f"完成第 {page} 页爬取")
  23. time.sleep(random.uniform(1, 3)) # 随机延迟
  24. # 保存数据到 CSV
  25. data = {"Title": titles, "Link": links}
  26. df = pd.DataFrame(data)
  27. df.to_csv("news.csv", index=False, encoding="utf-8-sig")
  28. print("新闻数据已保存到 news.csv")
复制代码

六、注意事项

  1. 避免法律风险

    • 爬取前阅读目标网站的使用条款。
    • 遵守 robots.txt 协议。
  2. 优化性能
    使用多线程或异步技术(如 asyncio、aiohttp)提高效率。

  3. 应对反爬
    熟练使用代理、延迟和伪装技巧。

 

 

 

 

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4008
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行