- 之前爬取總是出現如圖的結果:手動打開url顯示的是想要的結果,但是爬取的時候data為空
- 嘗試了多種方法,偶然得到了想要的結果:
這是多次實驗中成功與不成功結果中構造的url
- 發現
1)得到想要結果,所構造的url中keyword=******與下一參數間沒有&鏈接
2)同樣的keyword=%E8%A1%97%E6%8B%8D,參用不同的方式:‘https://www.toutiao.com/api/search/content/?keyword=%E8%A1%97%E6%8B%8D’+urlencode(params)
requests.get(‘https://www.toutiao.com/api/search/content/?’,params=params)
得到的url結果是不一樣的,前一個的keyword不變,還是%E8%A1%97%E6%8B%8D,后一種方式得到的keyword變成了%25E8%25A1%2597%25E6%258B%258D
- 因為不是科班專業,僅僅根據自己所學的比較淺薄的知識連蒙帶猜得出來的結果,還希望有專業人士解釋一下,嘻嘻。
- 附上部分代碼
import requests from urllib.parse import urlencode def get_page(offset): params={ 'aid':24, 'app_name':'web_search', 'format':'json', 'offset':offset, 'autoload':'true', 'count':20, 'en_qc':1, 'cur_tab':1, 'from':'search_tab', 'pd':'synthesis' } headers={ 'X-Requested-With':'XMLHttpRequest', 'Cookies':'tt_webid=6788393831844185614; WEATHER_CITY=%E5%8C%97%E4%BA%AC; tt_webid=6788393831844185614; csrftoken=0fd39b0f026752a8f38a902ab9226d44; s_v_web_id=k64mh7pe_9IueD6zl_X1iG_4smt_8Dkd_SMrb5NXXMR8G; __tasessionId=naf9b8ylp1580623604878', 'Host':'www.toutiao.com', 'Referer':'https://www.toutiao.com/search/?keyword=%E8%A1%97%E6%8B%8D', 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } try: url='https://www.toutiao.com/api/search/content/?keyword=%E8%A1%97%E6%8B%8D'+urlencode(params) response=requests.get(url,headers=headers) response.raise_for_status response.encoding=response.apparent_encoding print(response.url) return response.json() except: print('爬取出錯')