使用Selenium与PyQuery抓取当当网畅销图书数据
在网页数据采集领域,面对动态加载内容的页面,传统的静态请求方式往往难以奏效。本文将介绍如何结合Selenium模拟浏览器行为,配合PyQuery解析HTML结构,实现对当当网图书热销榜的完整数据抓取。
首先确保开发环境已安装必要的依赖库。通过以下命令安装Selenium:
pip install selenium
若需离线安装,可前往PyPI官网下载对应版本的wheel文件,执行pip本地安装指令完成部署。验证安装是否成功,可在Python交互环境中尝试导入selenium模块。
由于目标网站采用JavaScript异步渲染,直接发送HTTP请求无法获取完整DOM结构。因此需要借助ChromeDriver驱动真实浏览器实例运行。请确认本地Chrome浏览器版本,并从Chromium官方项目下载兼容版本的驱动程序。建议将chromedriver.exe置于Python环境的Scripts路径下,以便系统全局调用。
分析目标页面发现,热销榜单按页码分页展示,URL结构清晰:
http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-24hours-0-0-1-1 <!-- 第一页 -->
http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-24hours-0-0-1-2 <// 第二页 -->
仅末尾数字随页码递增变化,便于构造批量请求地址。使用Selenium启动Chrome实例后,设置显式等待机制以应对网络延迟:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import pyquery as pq
import csv
driver = webdriver.Chrome()
waiter = WebDriverWait(driver, 10)
def fetch_page(page_num):
target_url = f'http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-24hours-0-0-1-{page_num}'
print(f'正在获取第 {page_num} 页数据')
try:
driver.get(target_url)
parse_book_content()
except Exception as e:
print(f'页面加载超时,重试中... {e}')
fetch_page(page_num)
页面加载完成后,利用page_source属性提取完整HTML源码,交由PyQuery进行DOM解析。定位商品列表容器,遍历每条图书记录并提取关键字段:
def parse_book_content():
html_content = driver.page_source
doc = pq(html_content)
for book_item in doc('.bang_list li').items():
record = {
'rank': book_item.find('.list_num').text(),
'title': book_item.find('.name').text(),
'image': book_item.find('.pic img').attr('src'),
'reviews': book_item.find('.star a').text(),
'recommendation': book_item.find('.tuijian').text(),
'author': book_item.find('.publisher_info a:nth-child(1)').text(),
'publish_date': book_item.find('.publisher_info span').text(),
'original_price': book_item.find('.price_r').text().replace('¥', ''),
'discount_price': book_item.find('.price_s').text(),
'ebook_price': book_item.find('.price_e').text().replace('电子书:', '').replace('¥', '')
}
save_to_csv(record)
为保证数据持久化存储,采用CSV格式输出结果。初始化文件头后,在每次解析出新记录时追加写入:
def init_csv():
with open('books_rank.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['排名', '书名', '封面图链接', '评论数', '推荐语', '作者', '出版日期', '原价', '折扣价', '电子书价格'])
def save_to_csv(book_data):
with open('books_rank.csv', 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow([
book_data['rank'], book_data['title'], book_data['image'],
book_data['reviews'], book_data['recommendation'], book_data['author'],
book_data['publish_date'], book_data['original_price'],
book_data['discount_price'], book_data['ebook_price']
])
主程序入口处设定爬取范围,循环调用指定页码的数据获取函数:
if __name__ == '__main__':
init_csv()
for page_index in range(1, 24): # 当前榜单共23页
fetch_page(page_index)
driver.quit()
执行完毕后将在本地生成books_rank.csv文件,包含完整的热销图书信息。该方法稳定可靠,适用于各类由前端框架动态渲染的内容抓取场景。