爬蟲新手大坑:爬取數據的時候一定要設置header偽裝成瀏覽器!!!!
在爬取某財經網站數據時由於沒有設置Header信息,直接被封掉了ip
后來設置了Accept、Connection、User-Agent三個參數后換了個ip登錄,成功請求到幾次數據后又被封掉ip
最后老老實實把所有header信息都加上后請求(其實還少了一個cookie),現在請求了幾十次還沒被封 (ಥ﹏ಥ)
代碼如下
#coding=utf-8 import requests from bs4 import BeautifulSoup headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding':'gzip,deflate,sdch', 'Accept-Language':'en,zh-CN;q=0.8,zh;q=0.6', 'Cache-Control':'max-age=0', 'Host':'www.xxx.com', #此處為財經網的主頁 'Connection':'keep-alive', 'Upgrade-Insecure-Requests':'1', 'Content-Type':'application/x-www-form-urlencoded', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36' } response = requests.get("http://www.xxxxxx.com", headers=headers) #請求的地址 soup = BeautifulSoup(response.content, 'html.parser') #返回的html信息用soup解析 print(response.status_code) #請求狀態碼 print(soup.prettify()) #以格式輸出html
有不懂的地方或者想要探討問題可以qq聯系:1163949417