1、為什么要設置headers?
在請求網頁爬取的時候,輸出的text信息中會出現抱歉,無法訪問等字眼,這就是禁止爬取,需要通過反爬機制去解決這個問題。
headers是解決requests請求反爬的方法之一,相當于我們進去這個網頁的服務器本身,假裝自己本身在爬取數據。
對反爬蟲網頁,可以設置一些headers信息,模擬成瀏覽器取訪問網站 。
2、 headers在哪里找?
谷歌或者火狐瀏覽器,在網頁面上點擊:右鍵–>檢查–>剩余按照圖中顯示操作,需要按Fn+F5刷新出網頁來
有的瀏覽器是點擊:右鍵->查看元素,刷新
注意:headers中有很多內容,主要常用的就是user-agent 和 host,他們是以鍵對的形式展現出來,如果user-agent 以字典鍵對形式作為headers的內容,就可以反爬成功,就不需要其他鍵對;否則,需要加入headers下的更多鍵對形式。
用Python下載一個網頁保存為本地的HTML文件實例1-中文網頁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import requests # 中文網頁:https://baike.so.com/doc/24386561-25208408.html url1 = 'https://baike.so.com/doc/24386561-25208408.html' #添加請求頭 headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE' } response_1 = requests.get(url1, headers = headers) response_1.encoding = 'utf-8' #第一種: # with open('steve_jobs2.html','w',encoding='utf-8') as f1: # f1.write(response_1.text) #第二種: f1 = open ( 'steve_jobs2.html' , 'w' ,encoding = 'utf-8' ) f1.write(response_1.text) c = response_1.text print (c) |
用Python下載一個網頁保存為本地的HTML文件實例2-英文網頁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import requests import re # 英文網頁:https://en.wikipedia.org/wiki/Steve_Jobs url2 = 'https://en.wikipedia.org/wiki/Steve_Jobs' response_2 = requests.get(url2) # 源碼都是Utf-8編碼 response_2.encoding = 'utf-8' #第一種: # with open('steve_jobs3.html','w',encoding='utf-8') as f2: # f2.write(response_2.text) #第二種: f2 = open ( 'steve_jobs3.html' , 'w' ,encoding = 'utf-8' ) f2.write(response_2.text) c = response_2.text print (c) |
到此這篇關于Python爬蟲中Requests設置請求頭Headers的方法的文章就介紹到這了,更多相關Python Requests設置請求頭Headers內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/ysblogs/article/details/88530124