设置代理

代理(英语:Proxy),也称网络代理,是一种特殊的网络服务,英文全称是(Proxy Server),其功 能就是代理网络用户去取得网络信息。形象的说:它是网络信息的中转站。代理服务器就好象一个大的 Cache,这样就能显著提高浏览速度和效率。

Requests模块设置代理的方式如下

import requests
# 设置代理,多用于爬虫
proxies = {"http":"http://12.34.56.79:9527",
           "https":"https://12.34.56.79:9527"}

# 1,普通的代理
res = requests.get(url="http://www.hnxmxit.com",proxies=proxies)
print(res.content.decode("utf-8"))

# 2,携带了登录的用户名和密码
# proxies1 = {"http":"http://用户名:密码@12.34.56.79:9527"}
# res = requests.get(url="http://hmxmxit.com",proxies=proxies1)
# print(res.content.decode("utf-8"))

超时设置

Requests模块可以设置接收数据的超时时间,超出设定的时间还没有数据返回,就抛出异常。超时设 置有两种类型表达:float 、tuple

timeout():以秒为单位

如果远端服务器很慢,你可以让 Request 永远等待,传入一个 None 作为 timeout 值

代码示例:

import requests,time
# 超时设置(以秒为单位)
# 1,接收数据的超时时间
print(time.time())
response = requests.get(url="http://www.hnxmxit.com",timeout=1)
print(time.time())

# 2,链接超时,接收超时
# 传入一个None 作为 timeout 值会一直等待
print(time.time())
res = requests.get(url="http://www.hnxmxit.com",timeout=(1,2))  # 以秒为单位(连接,接收)
print(time.time())

重定向设置

在请求url时,服务器会自动把我们的请求重定向,可以使用response.history来查看重定向。如果不想进行自 动重定向,可以用参数allow_redirects关闭

设置重定向开关:allow_redirects:True/False

代码示例:

import requests
# 设置重定向开关:allow_redirects:True/False
res = requests.get(url="http://www.360buy.com",allow_redirects=True)  # 设置重定向开关
print(res.history)  # 查看重定向历史
print(res.url)

查看执行结果:

python 代理服务器 指定网卡 python http代理服务器_python 代理服务器 指定网卡