目前只能爬取100条左右数据,还请大佬多多指导
代码由下面链接提供修改而成
使用了 EdgeDriver服务
该服务需要下载与自己版本相符的驱动并配置环境变量
在这个网站上下载驱动:Microsoft Edge WebDriver |Microsoft Edge 开发人员
【爬虫】Python实现爬取淘宝商品信息(超详细)_python爬取淘宝数据-CSDN博客
完整代码
import os
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 openpyxl as op
import time
from pyquery import PyQuery as pq
# 启动EdgeDriver服务
options = webdriver.EdgeOptions()
options.add_experimental_option("excludeSwitches", ['enable-automation'])
driver = webdriver.Edge(options=options)
driver.maximize_window()
wait = WebDriverWait(driver, 20)
count = 1 # 定义全局变量 count
# 爬取给定URL的商品信息
def get_goods_from_url(url):
global count # 使用全局变量 count
driver.get(url)
# 获取商品前固定等待20秒,刷新/滑动界面,使所有信息都加载完成
time.sleep(20)
html = driver.page_source
doc = pq(html)
# 提取所有商品的共同父元素的类选择器
items = doc('div.Comment--KkPcz74T').items()
product_info = []
for item in items:
try:
ptitle = item.find('.userName--mmxkxkd0').text()
# 定位日期型号
price_int = item.find('.meta--TDfRej2n').text()
# 定位评价
deal = item.find('.content--FpIOzHeP').text()
# 构建商品信息字典
product = {
'Num': count,
'ptitle': ptitle,
'price_int': price_int,
'deal': deal,
}
print(product)
product_info.append(product)
count += 1 # 下一行
except Exception as e:
print(f"Error processing item: {e}")
return product_info
if __name__ == '__main__':
url = 'https://detail.tmall.com/item.htm?id=624028279786' # 修正 URL
# 爬取数据
product_info = get_goods_from_url(url)
# 保存Excel表格
if product_info:
wb = op.Workbook()
ws = wb.active
# 添加表头
ws.append(['序号', '用户名', '日期型号', '定位评价'])
# 遍历所有评价信息并写入Excel
for review in product_info:
ws.append(list(review.values()))
# 获取用户输入的文件名
filename = input("请输入存储文件名称:")
filepath = os.path.join('D:\\爬虫\\', filename + '.xlsx')
wb.save(filepath)
print(f'{filename}.xlsx 存储成功~')
driver.quit() # 关闭 WebDriver
862

被折叠的 条评论
为什么被折叠?



