示例语句: html = requests.get(url,headers=headers,proxies=proxy,timeout=3)
本篇文章将解析上述划线部分:函数的返回值以及四个参数的含义及用法
专题:【python异常处理】
专题:【python断言】
Uniform Resource Locator:统一资源定位符(网页地址)
使用:
url = "https://www.baidu.com"
User Agent中文名为用户代理,简称 UA:
它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本、浏览器的版本、渲染引擎和语言等参数信息;
该用户代理是一个长长的字串,在request.get()中需要以字典的形式进行表示:
headers = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)")}
技巧:
可以将所有的User Agent放在一个list中,然后使用random.choice()来从该list中随机选取一个
user_agent = [
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)"
]
headers = {"User-Agent":random.choice(user_agent)}
Proxy对象:proxy={'协议':'ip:端口'}
示例:proxies = {"proxies":{"http":"183.159.94.169:18118"}}
使用:requests.get(url,headers=headers,proxies=proxies)
使用get()方法返回值会保存为一个response对象;
该对象有以下几个主要属性:
status_code #请求返回的状态码,200表示连接成功,404表示连接失败
text #根据返回的response中的encoding编码对内容进行解码
content #直接返回字节码(Bytes)
encoding #编码方式,可以修改:r.encoding = "utf-8"
headers #头文件信息
url #返回访问url该对象的方法主要由两个:
json()方法: 内置的JSON解码器(JavaScript Object Notation符号/注释/记号,自动转换返回的json格式数据)
超时设置:参数值为时间(/s)
在向需要访问的URL发送访问请求后,如果在上述设置时间内没有回应就返回错误信息
附加:request的异常库: requests.RequestExceptoin(可以使用python的异常处理语句输出错误信息)
import requests
URL = "https://www.52pojie.cn/forum.php?mod=forumdisplay&fid=16&page=1"
headers = {"User-Agent":"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"}
proxies = {"proxies":{"http": "61.216.36.80:80"}}
try:
r = requests.get(URL,headers = headers,proxies=proxies)
r.raise_for_status()
except requests.RequestException as e:
print(e)
else:
r.encoding = "UTF-8"
result = r.text
print(type(result),result,sep="\n")
print()语句部分解释:print(a,b,sep = " ",end = "\n\n")
sep = " ":在a和b输出之间使用sep的内容分隔
end = "\n\n":输出结束符(默认为一个换行符\n)