爬虫4 proxy 使用代理服务器发送请求

时间:2020-04-28
本文章向大家介绍爬虫4 proxy 使用代理服务器发送请求,主要包括爬虫4 proxy 使用代理服务器发送请求使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

简述:使用代理服务器发送请求,隐藏自己的真是ip...

  request = Request(url, headers=headers)

  1. 使用urllib.request下的ProxyHandler模块,来加载代理ip,生成对象

  2. 使用urllib.request下的build_opener模块,加载代理对象

"""proxy, 使用代理地址,防止本机ip被爬取的网站查封
    1. 使用代理ip信息, 查询‘ip代理’, 此处使用‘快代理’中的代理地址
    1. ProxyHandler库, 加载代理ip地址
    2. build_opener库, 类似urlopen,是用来做代理地址请求的
"""

from urllib.request import Request, build_opener
from fake_useragent import UserAgent
from urllib.request import ProxyHandler


url = "http://httpbin.org/get"      # 此网址可以发返回发送的请求头信息
headers = {
    'User-Agent': UserAgent().chrome
}
request = Request(url, headers=headers)

# 创建代理地址对象
handler = ProxyHandler({'http': '182.46.197.33:9999'})

# 创建代理请求对象, 加载代理地址对象
opener = build_opener(handler)

# 发送请求, 返回响应
response = opener.open(request)
info = response.read()
print(info.decode())

原文地址:https://www.cnblogs.com/leafchen/p/12794016.html