您的位置:首页 > 编程语言 > Python开发

python3使用代理ip伪装爬虫访问网站

2017-06-03 22:38 941 查看
这是学习小甲鱼的视频写的一毛一样的程序

'使用代理ip伪装爬虫'

'''
使用代理第一步: proxy_support = urllib.request.ProxyHandler({})
使用代理第二步: opener = urllib.request.build_opener(proxy_support)
使用代理第三步: urllib.request.install_opener(opener);opener.open(url)
'''
import urllib.request

url = 'http://www.whatismyip.com.tw'

proxy_handle = urllib.request.ProxyHandler({'http':'220.249.185.178:9999'})
#{'类型':'代理ip:端口'}

opener = urllib.request.build_opener(proxy_handle)
#创建一个opener

urllib.request.install_opener(opener)
#安装一个opener
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
#访问opener,返还给response,将response解码

print(html)


报错:

urllib.error.URLError: <urlopen error [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。>


找腿子,分析一波,是www.whatismyip.com.tw这个网站被爬的太多次,就和之前的有道一般,搜拉拉的升级了网站,不能用python直接刚,然后腿子加了个headers,换个ip,成功执行,与想象中的效果一样。下面是润色过的代码:

'代理ip'

import urllib.request
import urllib.error

url = 'http://www.whatismyip.com.tw'
proxy_handle = urllib.request.ProxyHandler({'http':'36.36.178.226:9797'})
opener = urllib.request.build_opener(proxy_handle)
urllib.request.install_opener(opener)
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}

try:
req = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
print(html)
except urllib.error.URLError as e:
print(e.reason)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: