老师,为什么我的数据,json.loads()报错加载不成功
来源:2-11 爬取淘宝网的数据

小禹o0
2018-12-26
写回答
1回答
-
淘宝网又更新了,做了调整,需要cookie才能拿到正确的HTML,否则,拿到的是登录页面的html,你可以按照如下步骤操作:
1.在PC端登录淘宝,找到对应的请求头
2.将登录后的cookie写入到请求头
text = requests.get(url, headers={ 'cookie': 'Your cookie' # 这你写你的cookie }).text
代码参考:
import requests import re import json def spider_tb(sn ,book_list=[]): url = 'https://s.taobao.com/search?q={0}'.format(sn) #获取html内容 text = requests.get(url, headers={ 'cookie': 'Your cookie' }).text # 使用正则表达式找到json对象 p = re.compile(r'g_page_config = (\{.+\});\s*', re.M) # print(text) rest = p.search(text) print(rest) if rest: print(rest.group(1)) data = json.loads(rest.group(1)) bk_list = data['mods']['itemlist']['data']['auctions'] print (len (bk_list)) for bk in bk_list: #标题 title = bk["raw_title"] print(title) #价格 price = bk["view_price"] print(price) #购买链接 link = bk["detail_url"] print(link) #商家 store = bk["nick"] print(store) book_list.append({ 'title' : title, 'price' : price, 'link' : link, 'store' : store }) print ('{title}:{price}:{link}:{store}'.format( title = title, price = price, link = link, store = store )) if __name__ == '__main__': spider_tb('9787115428028')
032018-12-26
相似问题