#淘宝爬取商品属性
具体代码如下:
import requests
import re
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return ""
def parsePage(ilt,html):
try:
plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"',html) #价格
tlt=re.findall(r'\"raw_title\"\:\".*?\"',html) #名称
ite=re.findall(r'\"item_loc\"\:\".*?\"',html) #地区
sal=re.findall(r'\"view_sales\"\:\".*?\"',html) #付款人数
nic=re.findall(r'\"nick\"\:\".*?\"',html) #店铺
lo=re.findall(r'\"comment_count\"\:\".*?\"',html) #评论数
for i in range(len(plt)):
price=eval(plt[i].split(":")[1])
title=eval(tlt[i].split(":")[1])
item=eval(ite[i].split(":")[1])
sales=eval(sal[i].split(":")[1])
nick=eval(nic[i].split(":")[1])
loc=eval(lo[i].split(":")[1])
ilt.append([price,title,item,sales,nick,loc])
except:
print("")
def printGoodsList(ilt):
tplt = "{:4}\t{:8}\t{:16}\t{:16}\t{:16}\t{:16}\t{:16}"
print(tplt.format("序号","价格","商品名称","地区","付款人数","店铺","评论数"))
count=0
for g in ilt:
count=count+1
print(tplt.format(count,g[0],g[1],g[2],g[3],g[4],g[5]))
print("")
def main():
goods="血压计" #可任意输入商品名称
depth=1 #页面数
start_url="https://s.taobao.com/search?q="+goods
infoList=[]
for i in range(depth):
try:
url=start_url +"&s="+str(44*i)
headers={
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
"cookie": "选取自己的Cookie"
}
html=requests.get(url,headers=headers)
parsePage(infoList,html.text)
except:
continue
printGoodsList(infoList)
main()
爬取结果:
1.request库的安装:
Win平台:“以管理员身份运行” cmd ,执行 pip install requests。
request库的安装测试:
import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
#输出 200
r.text
print(r.text)
2.cookie 的查找
登录你的淘宝账号
获取方法:按F12,打开开发者工具,然后按ctrl+F,在搜索页面任意搜索一个物品名字,如血压计。接着双击图上指出的位置,在header下面找到cookie的内容。