您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關python爬蟲如何添加請求頭,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
request
import requests headers = { # 'Accept': 'application/json, text/javascript, */*; q=0.01', # 'Accept': '*/*', # 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7', # 'Cache-Control': 'no-cache', # 'accept-encoding': 'gzip, deflate, br', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36', 'Referer': 'https://www.google.com/' } resp = requests.get('http://httpbin.org/get', headers=headers) print(resp.content)
urllib
import urllib, urllib2 def get_page_source(url): headers = {'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.8', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36', 'Connection': 'keep-alive', 'Referer': 'http://www.baidu.com/' } req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req) page_source = response.read() return page_source
phantomjs請求頁面
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities def get_headers_driver(): desire = DesiredCapabilities.PHANTOMJS.copy() headers = {'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.8', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36', 'Connection': 'keep-alive', 'Referer': 'http://www.baidu.com/' } for key, value in headers.iteritems(): desire['phantomjs.page.customHeaders.{}'.format(key)] = value driver = webdriver.PhantomJS(desired_capabilities=desire, service_args=['--load-images=yes'])#將yes改成no可以讓瀏覽器不加載圖片 return driver
關于“python爬蟲如何添加請求頭”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。