当前位置: 首页 > news >正文

爬虫学习案例4

爬取猪八戒网站数据:2024-12-12

使用xpath解析元素,安装依赖库

pip install lxml

使用selenium步骤我的上篇博客有提到,这里就不重复了
selenium使用博客导航

# 安装pip install lxml,使用xpath
from lxml import etree
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options# 设置Chrome选项
chrome_options = Options()
chrome_options.add_argument("--headless")  # 无头模式,不打开浏览器窗口
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")# 设置ChromeDriver路径
service = Service('D:\\env\\python3\\chromedriver.exe')
keyword = "微信小程序"
url = f"https://www.zbj.com/fw/?k={keyword}"
# 初始化WebDriver
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get(url)
# 等待页面加载
time.sleep(2)  # 等待内容加载html = driver.page_source # 原页面
# 使用xpath提取元素
tree = etree.HTML(html)
divList = tree.xpath("/html/body/div[2]/div/div/div[3]/div[1]/div[4]/div/div[2]/div[1]/div[2]/div")
for divItem in divList:price_elements = divItem.xpath("./div/div[3]/div[1]/span/text()")title_elements = divItem.xpath("./div/div[3]/div[2]/a/span/text()")company_elements = divItem.xpath("./div/div[5]/div/div/div/text()")sales_elements = divItem.xpath("./div/div[3]/div[3]/div[1]/div/span[2]/text()")good_elements = divItem.xpath("./div/div[3]/div[3]/div[2]/div/span[2]/text()")price = price_elements[0].strip("¥") if price_elements else "N/A"title = keyword.join(title_elements) if title_elements else "N/A"company = company_elements[0] if company_elements else "N/A"sales = sales_elements[0] if sales_elements else "N/A"good = good_elements[0] if good_elements else "N/A"print(f"价格: {price}")print(f"标题: {title}")print(f"商铺名: {company}")print(f"销量: {sales}")print(f"好评: {good}")print("下一家***********************")
driver.quit()  # 关闭浏览器

运行效果:
在这里插入图片描述
在这里插入图片描述
猪八戒网每次请求的数据都会随机打乱,所以控制台输出的顺序可能与页面的对应不上。
通过keyword变量可以更换查询内容。可以试试其他关键字。。。

http://www.lryc.cn/news/503136.html

相关文章:

  • Angular模块化应用构建详解
  • 51c大模型~合集89
  • 【蓝桥杯备战】Day 1
  • FedAdam算法:供给方信用,数据质量;更新一致性
  • 内存卡格式化后的数据恢复全攻略
  • 介绍交叉熵损失(Cross-Entropy Loss)以及交叉熵在对比学习中的应用:中英双语
  • RabbitMQ的几个概念
  • Ollama部署大模型并安装WebUi
  • Debedium如何忽略Oracle的purge命令
  • PlantUML 语言
  • linux的 .so和.ko文件分别是什么?主要区别是什么?
  • XX服务器上的npm不知道咋突然坏了
  • 数据结构(优先级队列 :Priority Queue)
  • nginx.conf 请求时间部分参数说明新手教程
  • 【Linux-ubuntu通过USB传输程序点亮LED灯】
  • 《开源时间序列数据:探索与应用》
  • 三相异步电动机跳闸的原因是什么?
  • 连续思维链Coconut ,打开LLM推理新范式
  • 阿里云数据库MongoDB版助力极致游戏高效开发
  • ESP32-S3模组上跑通ES8388(29)
  • 使用ElasticSearch实现全文检索
  • 通过k-means对相似度较高的语句进行分类
  • 国信华源科技赋能长江蓄滞洪区水闸管护项目验收成果报道
  • HTML:表格重点
  • wine的使用方法
  • Linux服务器离线安装unzip包
  • Excel拆分脚本
  • Mybatis---事务
  • 企业直播间媒体分发新闻转播拉流推广名单(金融财经科技类)
  • 华为FreeBuds Pro 4丢了如何找回?(附查找功能使用方法)