import requests
import re
from bs4 import BeautifulSoup
def getHtmlText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
print("加载超时")
def parsePage(ilt,html):
try:
plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html) //这两行re表达式,至关重要
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 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(lit):
tplt="{:4}\t{:8}\t{:16}"
print(tplt.format("序号","价格","商品名称"))
count=0;
for g in lit:
count=count+1
print(tplt.format(count,g[0],g[1]))
def main():
goods="书包"
depth=2;
start_url="https://s.taobao.com/search?q="+goods
infolist = []
for i in range(depth):
try:
url = start_url+'&s='+str(i*44)
html=getHtmlText(url)
parsePage(infolist,html)
except:
continue
printGoodslist(infolist)
main()
淘宝商品比价定向爬虫
最新推荐文章于 2021-01-18 19:30:14 发布