如何利用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()猜您想看
-
ElasticSearch启动失败问题汇总和解决方法是什么
1. Elas...
2023年05月26日 -
Python中调试代码的方式有哪些
在Python...
2023年07月20日 -
Qt怎么实现人脸识别客户端
1、使用Qt创...
2023年05月26日 -
电脑上的游戏中断怎么处理?
如何处理电脑上...
2023年04月24日 -
Git Reset三种模式hard,soft,mix各自的用法
Git Res...
2023年05月26日 -
一名专业的SEO优化员提升自我修养的方法有哪些
SEO优化是一...
2023年07月22日