!只用于学习用途!
plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
:获得商品价格和view_price字段,并保存在plt中
tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
:获得商品名称和raw_price字段,并保存在tlt中
price = eval(plt[i].split(':')[1])
:使用冒号分隔键值对,去掉前面的view_price字段,只获取其中价格部分
tplt = "{:4}\t{:8}\t{:16}"
:第一个位置给出大小为4,第二个位置大小为8,第三个位置大小为16
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)
for i in range(len(plt)):
price = eval(plt[i].split(':')[1])
title = eval(tlt[i].split(':')[1])
ilt.append([price , title])
except:
print("") def printGoodsList(ilt):
tplt = "{:4}\t{:8}\t{:16}"
print(tplt.format("序号", "价格", "商品名称"))
count = 0
for g in ilt:
count = count + 1
print(tplt.format(count, g[0], g[1])) def main():
goods = '书包'
depth = 3
start_url = 'https://s.taobao.com/search?q=' + goods
infoList = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44*i)
html = getHTMLText(url)
parsePage(infoList, html)
except:
continue
printGoodsList(infoList) main()