python请求头cache-control可以更改嘛_如何设置爬虫请求头?这些python的代码可以帮到你...

【摘要】爬虫作为python众多功能中的其中一种,有着不可或缺的地位,那么如何设置爬虫请求头?这些python的代码可以帮到你,这些内容也许对python学习有帮助,毕竟实践出真知,所以你要知道如何设置爬虫请求头?这些python的代码可以帮到你。

一、如何设置爬虫请求头——requests设置请求头:

import requests

url="http://www.targetweb.com"

headers={

'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

'Cache-Control':'max-age=0',

'Connection':'keep-alive',

'Referer':'http://www.baidu.com/',

'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400'}

res=requests.get(url,headers=headers)

#图片下载时要用到字节流,请求方式如下

#res=requests.get(url,stream=True,headers)

二、如何设置爬虫请求头——Selenium+Chrome请求头设置:

from selenium import webdriver

options = webdriver.ChromeOptions()

options.add_argument('lang=zh_CN.UTF-8')# 设置中文

options.add_argument('user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400"')# 设置头部

browser = webdriver.Chrome(chrome_options=options)

url="http://www.targetweb.com"

browser.get(url)

browser.quit()

三、如何设置爬虫请求头——selenium+phantomjs请求头设置:

from selenium import webdriver

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

des_cap = dict(DesiredCapabilities.PHANTOMJS)

des_cap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400")

browser = webdriver.PhantomJS(desired_capabilities=des_cap)

url="http://www.targetweb.com"

browser.get(url)

browser.quit()

四、如何设置爬虫请求头——爬虫框架scrapy设置请求头:

在settings.py文件中添加如下:

DEFAULT_REQUEST_HEADERS = {

'accept': 'image/webp,*/*;q=0.8',

'accept-language': 'zh-CN,zh;q=0.8',

'referer': 'https://www.baidu.com/',

'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400',}

五、如何设置爬虫请求头——Python异步Aiohttp请求头设置:

import aiohttp

url="http://www.targetweb.com"

headers={

'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',

'Cache-Control':'max-age=0',

'Connection':'keep-alive',

'Referer':'http://www.baidu.com/',

'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400'}

asyncwithaiohttp.ClientSession(headers=headers)assession:

asyncwithsession.get(url)asresp:

print(resp.status)

print(awaitresp.text())

以上就是《如何设置爬虫请求头?这些python的代码可以帮到你》的全部内容,这些python的实践方法学会了,你的python一定会突飞猛进,环球网校的小编也祝大家python学习之路顺利。如果你想知道更多的python编程知识,可以点击下方资料下载链接。

你可能感兴趣的:(python请求头cache-control可以更改嘛_如何设置爬虫请求头?这些python的代码可以帮到你...)