如何利用selenium库爬取京东python书籍一百页存入csv
1. 导入所需的库
首先,我们需要导入selenium库,以及csv库,以及相关的浏览器驱动,下面的代码展示了如何导入需要的库:
from selenium import webdriver
import csv
from selenium.webdriver.chrome.options import Options2. 创建浏览器驱动
接下来,我们需要创建一个浏览器驱动,比如Chrome浏览器,以便爬取京东python书籍的信息,下面的代码展示了如何创建Chrome浏览器驱动:
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://search.jd.com/Search?keyword=python")3. 爬取信息并存入csv
最后,我们可以使用selenium库来爬取京东python书籍的信息,并存入csv文件中,下面的代码展示了如何爬取一百页的python书籍信息:
csv_file = open('jd_python_books.csv', 'w', newline='', encoding='utf-8')
writer = csv.writer(csv_file)
writer.writerow(['title', 'price', 'comment'])
for i in range(100):
try:
books = driver.find_elements_by_xpath('//div[@class="gl-i-wrap"]')
for book in books:
title = book.find_element_by_xpath('.//div[@class="p-name"]/a/em').text
price = book.find_element_by_xpath('.//div[@class="p-price"]/strong/i').text
comment = book.find_element_by_xpath('.//div[@class="p-commit"]/strong/a').text
writer.writerow([title, price, comment])
next_page = driver.find_element_by_xpath('//a[@class="pn-next"]')
next_page.click()
except:
break
csv_file.close()猜您想看
-
hadoop心跳时间与冗余快清除方法是什么
1. Hado...
2023年07月22日 -
如何在Docker中进行容器回滚?
Docker容...
2023年04月16日 -
ASP.NET Core性能优化的方法是什么
ASP.NET...
2023年07月20日 -
keras如何实现图像风格转换 -
1. 简介图像...
2023年07月22日 -
如何在微信中设置聊天背景音乐?
一、微信聊天背...
2023年05月15日 -
QT系统中怎么安装交叉编译工具链
什么是交叉编译...
2023年07月22日