爬虫学习案例4

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

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

powershell 复制代码
pip install lxml

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

python 复制代码
# 安装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变量可以更换查询内容。可以试试其他关键字。。。

相关推荐
xinzheng新政1 小时前
纸板制造胶工艺学习1
学习·制造
楼田莉子2 小时前
C++学习之继承
开发语言·c++·学习·visual studio
电商API_180079052473 小时前
微店商品详情接口micro.item_get请求参数响应参数解析
大数据·数据库·人工智能·爬虫
李白你好3 小时前
一个高效的阿里云漏洞库爬虫工具,用于自动化爬取和处理CVE数据
爬虫·自动化·cve漏洞
Asu52024 小时前
思途SQL学习 0729
数据库·sql·学习
一位搞嵌入式的 genius6 小时前
暑期自学嵌入式——Day10(C语言阶段)
linux·笔记·学习·嵌入式c语言
晨非辰8 小时前
#C语言——学习攻略:深挖指针路线(三)--数组与指针的结合、冒泡排序
c语言·开发语言·数据结构·学习·算法·排序算法·visual studio
先生沉默先8 小时前
Docker学习日志-Docker容器配置、Nginx 配置与文件映射
学习·nginx·docker
Brookty14 小时前
Java线程安全与中断机制详解
java·开发语言·后端·学习·java-ee
飞速移动的代码菌14 小时前
【DataWhale】快乐学习大模型 | 202507,Task08笔记
笔记·学习