如何利用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()猜您想看
-
linux如何安装ipfs
1、安装IPF...
2023年05月26日 -
网站导航怎么做SEO优化
网站导航SEO...
2023年05月22日 -
如何在EXSI中创建虚拟交换机
ESXi是VM...
2023年04月17日 -
怎么用Java实现判断括号的合法性
一、什么是括号...
2023年05月26日 -
为什么HashMap的加载因子是0.75
1. 什么是H...
2023年07月22日 -
Windows XP 如何安装和升级
如何安装和升级...
2023年04月15日