python爬取淘宝商品详情页数据
(编辑:jimmy 日期: 2025/11/6 浏览:3 次 )
在讲爬取淘宝详情页数据之前,先来介绍一款 Chrome 插件:Toggle JavaScript (它可以选择让网页是否显示 js 动态加载的内容),如下图所示:
当这个插件处于关闭状态时,待爬取的页面显示的数据如下:
当这个插件处于打开状态时,待爬取的页面显示的数据如下:
评论数据的链接可以直接访问(和价格信息找法类似),这里我知己去访问它,如下图所示:
"htmlcode">
# filename:spider_taobao.py
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import re
import urllib2
def spider_taobao(url):
headers = {
'Accept':'application/json, text/plain, */*',
'Accept-Language':'zh-CN,zh;q=0.3',
'Referer':'https://item.taobao.com/item.htm',
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Connection':'keep-alive',
}
goods_id = re.findall('id=(\d+)', url)[0]
try:
req = urllib2.Request(url=url, headers=headers)
res = urllib2.urlopen(req).read().decode('gbk', 'ignore')
except Exception as e:
print '无法打开网页:', e.reason
try:
title = re.findall('<h3 class="tb-main-title" data-title="(.*"', res)
title = title[0] if title else None
line_price = re.findall('<em class="tb-rmb-num">(.*"https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm".format(goods_id)
price_req = urllib2.Request(url=purl, headers=headers)
price_res = urllib2.urlopen(price_req).read()
data = list(set(re.findall('"price":"(.*"', price_res)))
# data列表中的价格可能是定值与区间的组合,也可能只是定值,而且不一定有序
real_price = ""
for t in data:
if '-' in t:
real_price = t
break
if not real_price:
real_price = sorted(map(float, data))[0]
# 45-53行为抓取评论数据,该数据也是动态加载的
comment_url = "https://rate.tmall.com/list_detail_rate.htm".format(goods_id)
comment_data = urllib2.urlopen(comment_url).read().decode("GBK", "ignore")
temp_data = re.findall('("commentTime":.*"days"', comment_data)
temp_data = temp_data if temp_data else re.findall('("rateContent":.*"reply"', comment_data)
comment = ""
for data in temp_data:
comment += data.encode('utf-8')
comment = comment if comment else "暂无评论"
except Exception as e:
print '数据抽取失败!!!'
print '商品名:', title
print '划线价格:', line_price
print '真实价格:', real_price
print '商品链接:', url
print '部分评论内容:', comment
if __name__ == '__main__':
#url = 'https://item.taobao.com/item.htm"请输入商品链接: ")
spider_taobao(url)
运行结果如下:
更多内容请参考专题《python爬取功能汇总》进行学习。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:Python抓取聚划算商品分析页面获取商品信息并以XML格式保存到本地






