如何利用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()猜您想看
-
如何设置 OpenWrt 路由器防火墙?
OpenWrt...
2023年04月17日 -
Pytorch Fashion Minst数据集读取方法
Pytorch...
2023年05月25日 -
C++ STL bind1st bind2nd bind 的使用方法
1、什么是C+...
2023年05月25日 -
如何解析Java中的Semaphore信号量
1、什么是Se...
2023年05月25日 -
如何解决Spring源码构建项目入eclipse后spring-cglib-repack-3.2.11.jar问题
一、Sprin...
2023年05月26日 -
C++ 中如何使用VideoWriter写入视频
<请开始...
2023年07月21日