一、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',
'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())
内容扩展:
1、为什么要设置headers?
在请求网页爬取的时候,输出的text信息中会出现抱歉,无法访问等字眼,这就是禁止爬取,需要通过反爬机制去解决这个问题。
headers是解决requests请求反爬的方法之一,相当于我们进去这个网页的服务器本身,假装自己本身在爬取数据。
对反爬虫网页,可以设置一些headers信息,模拟成浏览器取访问网站 。
2、 headers在哪里找?
谷歌或者火狐浏览器,在网页面上点击:右键–>检查–>剩余按照图中显示操作,需要按Fn+F5刷新出网页来
有的浏览器是点击:右键->查看元素,刷新
以上就是python爬虫请求头设置代码的详细内容,更多关于python爬虫请求头如何设置的资料请关注考高分网其它相关文章!



