selenium爬虫爬取当当网书籍信息 | 最新!

如果对selenium不了解的话可以到下面的链接中看基础内容:

selenium爬取有道翻译-CSDN博客

废话不多说了下面是代码并且带有详细的注释:

爬取其他类型的书籍和下面基本上是类似的可以自行更改。

python 复制代码
# 导入所需的库
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import csv

# 创建一个Chrome浏览器实例,并设置为无头模式(不显示界面)
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

# 访问当当网首页
driver.get('https://www.dangdang.com/')

# 在搜索框中输入关键词"科幻"
key = driver.find_element(By.ID, "key_S")
key.send_keys("科幻")

# 点击搜索按钮
element = driver.find_element(By.ID, "search_btn")
driver.execute_script("arguments[0].click();", element)

# 创建CSV文件并写入表头
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['标题', '价格'])

# 循环爬取前3页的书籍信息
for i in range(3):
    # 获取当前页面的所有书籍列表
    shoplist = driver.find_elements(By.CSS_SELECTOR, ".shoplist li")

    # 遍历每本书的信息
    for li in shoplist:
        # 获取书名
        title = li.find_element(By.CSS_SELECTOR, "a").get_attribute("title")

        # 获取价格
        price = li.find_element(By.CSS_SELECTOR, ".search_now_price").text

        # 将获取到的数据添加到CSV文件中
        with open('output.csv', 'a', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow([title, price])

    # 获取下一页的链接并点击
    next = driver.find_element(By.LINK_TEXT, "下一页")
    next.click()

    # 等待页面加载完成
    time.sleep(2)

# 当用户输入1时,退出浏览器
if input('1'):
    driver.quit()

下面是运行效果

代码是最新的,在这一段时间内一定是可以运行的

如果有啥问题可以问我看到一定会回复大家,如果大家喜欢可以作者点赞和关注

大家的支持是我创作下去的最大动力!

相关推荐
SelectDB4 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码12 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab