编写Python爬虫的基本步骤如下:
安装必要的库
`requests`:用于发送HTTP请求。
`BeautifulSoup`:用于解析HTML/XML文档。
`lxml`:用于解析HTML文档,特别是当需要使用XPath时。
`selenium`:用于处理JavaScript动态内容。
导入库
import requests
from bs4 import BeautifulSoup
from lxml import etree
发送请求
url = 'https://example.com' 目标网站的URL
response = requests.get(url) 发送HTTP GET请求
解析响应
if response.status_code == 200: 检查请求是否成功
soup = BeautifulSoup(response.text, 'html.parser') 使用BeautifulSoup解析HTML
或者使用lxml
tree = etree.HTML(response.text)
else:
print('请求失败:', response.status_code)
提取数据
示例:提取网页标题
title = soup.title.string
print(title)
处理分页 (如果需要):查找下一页链接
next_page = soup.find('a', {'class': 'next'})
if next_page:
next_page_url = next_page['href']
递归或循环请求下一页,直到没有下一页
查找下一页链接
next_page = soup.find('a', {'class': 'next'})
if next_page:
next_page_url = next_page['href']
递归或循环请求下一页,直到没有下一页
处理JavaScript(如果需要):
from selenium import webdriver
driver = webdriver.Chrome() 启动Chrome WebDriver
driver.get(url) 加载目标URL
提取数据
data = driver.find_elements_by_xpath('//div[@]')
for item in data:
print(item.text)
driver.quit() 关闭WebDriver
保存数据
示例:保存到CSV文件
import csv
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['标题', '描述', '链接'])
for item in data:
writer.writerow([item.find_element_by_xpath('//h1').text,
item.find_element_by_xpath('//p').text,
item.find_element_by_xpath('//a')['href']])
请根据实际需要调整代码中的URL、选择器、解析方式等。记得在编写爬虫时遵守目标网站的`robots.txt`规则,并尊重版权和隐私政策。