马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
如题,我的代码抓不到淘宝的商品,不知道用什么办法确定以及绕过反爬机制。求大神解惑import requests
import re
def gethtmltext(url):
try:
kv = {'cookie':'sca=cdd952b0; cna=cm8hFgVY6isCAW+0ai8EgOrj; aimx=1n4lF98C5mwCAWx3t6cZd55B_1587450070; cnaui=2200738114438; aui=2200738114438; cdpid=UUphyu7orn4%252Ft8bQFQ%253D%253D; cad=172c034b847802205482156047270001; cap=c761; atpsidas=962aed7a82779641e0740610_1592369935_2; tbsa=43581b04af757d1725743750_1592369935_1; atpsida=03dc10c30f9fb1ace4f9c56e_1592369935_1',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36 Edg/83.0.478.45',
':authority':'www.taobao.com',':method':'GET',':path':'/markets/search/search-suggest-history-iframe',':scheme':'https','accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'accept-encoding':'gzip, deflate, br','accept-language':'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6'}
r = requests.get(url,headers = kv,timeout = 20)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text)
return r.text
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])
return ilt
except:
print('!')
def printgoodslist(ilt):
tplt = '{0:^4}\t{0:^8}\t{2:^16}'
print(tplt.format('序号','价格','商品名称'))
count = 0
for g in ilt:
count += 1
print(tplt.format(count,g[0],g[1]))
if __name__ == '__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(44*i)
html = gethtmltext(url)
parsepage(infolist,html)
except:
continue
printgoodslist(infolist)
|