import requests
import re
def getHtml(keyword, page=1):
payload = {'q': keyword,
's': str((page-1)*44)}
headers = {'authority': 's.taobao.com',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
'cookie': 'Your cookie'}
url = 'https://s.taobao.com/search'
response = requests.get(url, params=payload, headers= headers, timeout=30)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
# def open_url(keyword, page=1):
# keyload = {'q': keyword, 's': str((page - 1) * 44), 'sort': 'sale-desc'}
def parserHtml(ilt, html):
try:
# item = re.search(r'g_page_config = (.*);\n', html) # 爬取整个商品页面
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])
return ilt
except:
print("解析错误")
def printList(ilt):
try:
tplt = "{:4}\t{:8}\t{:16}"
print(tplt.format("序号", "价格", "名称"))
count = 0
for i in ilt:
count += 1
print(tplt.format(count, i[0], i[1]))
except:
print("打印出现错误")
def main():
ilt = []
keyword = input("你想搜索的商品")
html = getHtml(keyword, page=2)
ilt = parserHtml(ilt, html)
printList(ilt)
main()