#使用urllib发起请求
from urllib import request
import ssl
#目标url
url = 'http://www.baidu.com/'
# request.urlopen():使用urlopen方法模拟浏览器发起请求
"""
url, 请求的目标url地址
data=None,默认情况为None,表示发起的是一个get请求,不为None,则发起的是一个post请求
timeout=,设置请求的超时时间
cafile=None, 设置证书
capath=None, 设置证书路径
cadefault=False, 是否要使用默认证书(默认为False)
context=None:是一个ssl值,表示忽略ssl认证
"""
#是一个ssl值,表示忽略ssl认证(如果请求出现了ssl证书认证错误,
# 我们就需要设置ssl._create_unverified_context(),忽略证书认证)
content = ssl._create_unverified_context()
response = request.urlopen(url,timeout=10,context=content)
#从response响应结果中获取参数
#状态码
code = response.status
print(code)
#获取页面源码的二进制数据
b_html = response.read()
print(type(b_html),len(b_html))
#获取响应的响应头部(Response Headers)
res_headers = response.getheaders()
print(res_headers)
#获取响应头中指定参数的值
cookie_data = response.getheader('Set-Cookie')
print(cookie_data)
#reason返回一个响应结果的原因
reason = response.reason
print(reason)
#将获取到的二进制数据,转换为字符串decode
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)
#如果请求要携带请求头
#需要先构建一个request对象
"""
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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
req = request.Request(url,headers=req_header)
#根据构建的req请求对象发起请求
response = request.urlopen(req)
response.status
response.read()
response.getheaders()
response.getheader('Server')
response.reason
网友评论