随机请求头是什么意思?

随机请求头是什么意思?,第1张

设置随机请求头是应对反爬虫的一种手段,如果某个相同的请求头对目标网站频繁进行访问,可能会被封禁。故此我们在爬虫的时候最好随机更改我们的请求头。

大家在爬虫中都设置请求头user-agent这个参数,在请求的时候,加入这个参数,就可以一定程度的伪装成浏览器,就不会被服务器直接识别为spider.demo.code。据我了解的,很多读者每次都是直接从network中去复制user-agent然后把他粘贴到代码中,这样获取的user-agent没有错,可以用。但是如果网站反爬措施强一点,用固定的请求头可能就有点问题,所以我们就需要设置一个随机请求头。

from urllib import request

import ssl

url = ' http://www.baidu.com/'

"""

url, 请求的目标url地址

data=None,默认情况为None,表示发起的是一个get请求,不为None,则发起的是一个post请求

timeout=,设置请求的超时时间 

cafile=None, 设置证书

capath=None, 设置证书路径

cadefault=False, 是否要使用默认证书(默认为False)

context=None:是一个ssl值,表示忽略ssl认证

"""

content = ssl._create_unverified_context()

response = request.urlopen(url,timeout=10,content=content)

code = response.status

print(code)

b_html = response.read()

print(type(b_html),len(b_html))

res_headers = response.getheaders()

print(res_headers)

cookie_data = response.getheader('Set-Cookie')

print(cookie_data)

reason = response.reason

print(reason)

str_html = b_html.decode('utf-8')

print(type(str_html))

with open('b_baidu.page.html','w') as file:

# file.write(b_html)

file.write(str_html)

"""

url:发起请求的url地址

data=None, 默认情况为None,表示发起的是一个get请求,不为None,则发起的是一个post请求

headers={},设置请求头(headers对应的数据类型是一个字典)

origin_req_host=None, (指定发起请求的域)

unverifiable=False,忽略SSL认证

method=None:指定发起请求的方式

"""

req_header = {

'User-Agent':'Mozilla/5.0 (X11Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'

}

req = request.Request(url,headers=req_header)

response = request.urlopen(req)

response.status

response.read()

response.getheaders()

response.getheader('Server')

response.reason

python2中:对于字符串和bytes类型的数据没有明显的区分

python3中:对于字符串和bytes类型的数据有明显的区分

将bytes类型的数据转换为字符串使用decode('编码类型')

将字符串转换为bytes类型的数据使用encode('编码类型')

bytearray和bytes类型的数据是有区别的:前者是可变的,后者是不可变的


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11532814.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-16
下一篇2023-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存