这篇文章将为大家详细讲解有关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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。