在 Python 中,爬虫是获取网页数据的常用工具。以下是六种常见的爬虫方法,涵盖了从简单的静态网页抓取到动态网页处理的多种场景。
1. 使用 requests + BeautifulSoup 抓取静态网页
这是最基础的爬虫方法,适用于静态网页(HTML 内容直接嵌入在网页中)。
示例代码:
import requests
from bs4 import BeautifulSoup
# 发送 HTTP 请求
url = 'https://example.com'
response = requests.get(url)
# 解析 HTML 内容
soup = BeautifulSoup(response.text, 'html.parser')
# 提取数据
title = soup.title.text
print(f'网页标题:{title}')
# 提取所有链接
links = soup.find_all('a')
for link in links:
print(link.get('href'))
适用场景:
- 静态网页数据抓取。
- 数据量较小的简单任务。
2. 使用 requests + 正则表达式提取数据
如果需要从网页中提取特定格式的数据(如邮箱、电话号码等),可以使用正则表达式。
示例代码:
import requests
import re
# 发送 HTTP 请求
url = 'https://example.com'
response = requests.get(url)
# 使用正则表达式提取邮箱
emails = re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', response.text)
print(emails)
适用场景:
- 提取特定格式的数据(如邮箱、电话号码、日期等)。
- 数据格式固定的场景。
3. 使用 Selenium 抓取动态网页
对于动态加载的网页(如通过 JavaScript 渲染的内容),可以使用 Selenium 模拟浏览器行为。
示例代码:
from selenium import webdriver
from selenium.webdriver.common.by By
driver = webdriver.Chrome()
url =
driver.get(url)
element = driver.find_element(By.CSS_SELECTOR, )
(element.text)
driver.quit()


