如何利用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()猜您想看
-
如何在Edge浏览器中启用“缩放”功能
在Edge浏览...
2023年05月13日 -
如何配置Kafka集群以使用PAM后端
概述Kafka...
2023年07月04日 -
Windows XP 如何进行系统加速
Windows...
2023年04月15日 -
如何在Linux中使用sha1sum命令计算文件校验和
在Linux中...
2023年05月06日 -
如何在Linux中使用chown命令更改文件所有权
Linu...
2023年05月05日 -
Ubuntu常用命令小结
Ubuntu是...
2023年07月23日