专业的编程技术博客社区

网站首页 > 博客文章 正文

Python Web Scraping 实战教程:快速掌握网页爬虫技巧

baijin 2024-12-18 14:41:49 博客文章 8 ℃ 0 评论

Python 的 Web Scraping 技术是数据采集的强大工具,适用于从网页中提取特定信息。以下是一个实战流程和代码示例,以帮助你快速上手。


1. 准备工作

安装依赖库
bash

pip install requests beautifulsoup4 lxml


    • requests:用于发送 HTTP 请求。
    • BeautifulSoup:解析 HTML 和 XML,提取内容。
    • lxml:支持快速解析 HTML。

2. 确定目标

选择一个目标网站,比如爬取某新闻网站的头条文章标题和链接。

目标网页:https://example-news-site.com
任务:抓取最新头条的标题和链接。


3. 基本代码

python



import requests

from bs4 import BeautifulSoup



# Step 1: 发送请求获取网页内容

url = "https://example-news-site.com"

headers = {

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"

}

response = requests.get(url, headers=headers)



# 检查请求是否成功

if response.status_code == 200:

# Step 2: 解析 HTML

soup = BeautifulSoup(response.text, "lxml")



# Step 3: 提取数据

headlines = soup.find_all("h2", class_="headline") # 根据网页的实际结构调整选择器

for headline in headlines:

title = headline.text.strip()

link = headline.find("a")["href"]

print(f"Title: {title}")

print(f"Link: {link}")

else:

print(f"Failed to fetch the page: {response.status_code}")




4. 代码解读

  1. HTTP 请求
  2. 使用 requests.get 发送 GET 请求。
  3. 设置 headers 模拟浏览器访问,避免被反爬虫机制屏蔽。
  4. HTML 解析
  5. soup = BeautifulSoup(response.text, "lxml") 将 HTML 转换为可操作对象。
  6. 使用 find_all 按标签和类名提取内容。
  7. 数据提取
  8. .text 提取标签内容。
  9. ["href"] 获取链接属性。

5. 注意事项

  1. 网站结构
  2. 网页结构可能经常变化,选择器需要及时调整。
  3. 反爬虫
  4. 添加随机 User-Agent。

设置请求间隔避免频繁访问:
python

import time

time.sleep(1)


  1. 合法性
  2. 确保遵守目标网站的 robots.txt 规则。

6. 高级功能

(1) 数据存储

将爬取的数据存入 CSV 文件:

python



import csv



# 存储数据

with open("headlines.csv", mode="w", encoding="utf-8", newline="") as file:

writer = csv.writer(file)

writer.writerow(["Title", "Link"]) # 表头

for headline in headlines:

title = headline.text.strip()

link = headline.find("a")["href"]

writer.writerow([title, link])



(2) 爬取多页数据

python



for page in range(1, 6): # 假设有 5 页

url = f"https://example-news-site.com/page/{page}"

response = requests.get(url, headers=headers)

# 同样的解析和提取逻辑



(3) 动态内容爬取

对于 JavaScript 渲染的内容,可以使用 selenium

bash



pip install selenium



配合浏览器驱动,完成动态加载的网页爬取。


7. 示例输出

plaintext



Title: Breaking News: Python Web Scraping

Link: https://example-news-site.com/breaking-news-python-web-scraping



Title: How to Build a Web Crawler

Link: https://example-news-site.com/build-web-crawler



本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表