第一种IP地址代理方式
from urllib import request
if __name__ == "__main__":
# 访问网址
url = 'http://www.ahaoboy.cn:888/'
# 这是代理IP
proxy = {
# 'http': '106.46.136.112:808'
# 'https': "https://112.112.236.145:9999",
"http": "http://118.193.107.174:80"
}
# 创建ProxyHandler
proxy_support = request.ProxyHandler(proxy)
# 创建Opener
opener = request.build_opener(proxy_support)
# 添加User Angent
opener.addheaders = [('User-Agent',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36')]
# 安装OPener
request.install_opener(opener)
# 使用自己安装好的Opener
response = request.urlopen(url)
# 读取相应信息并解码
html = response.read().decode("utf-8")
# 打印信息
print(html)
第二种IP地址代理方式
import requests, sys
url = 'http://jingcaiyuedu.com/'
proxy = {
'http':'121.43.170.207:3128'
}
try:
response = requests.get(url, proxies=proxy, timeout=1)
print(response.content.decode('utf-8'))
except requests.exceptions.ConnectionError:
print('超时')