个人专题Python 紀錄程序员

建立自己的代理IP池

2017-02-19  本文已影响393人  dalalaa

上次写观影排雷的时候因为爬取次数太多被豆瓣封了IP,在网友的提示下,用代理IP试了一下,免费代理IP的效率不高,也还凑合。

Paste_Image.png

用爬虫搜集免费IP

可以选择一个免费IP网站爬取,比如说有代理

<code>
ipList = []
serverList = []
urls = 'http://www.youdaili.net/Daili/QQ/31893.html'
def findIP(url):
req = urllib.request.Request(url=urls, headers={
'User-Agent': ' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'})
try:
handler = urllib.request.urlopen(req)
except HTTPError as e:
content = e.read()
soup = BeautifulSoup(handler, "html.parser")
p = soup.find('div', {'class': "content"})
ips = p.findAll('p')
for item in ips:
item = str(item)
pattern = re.findall(r'>(.+?):', item)
server = re.findall(r':(.+?)@', item)
ipList.append(pattern)
serverList.append(server)
# print(ipList, serverList)
findIP(urls)
for i in range(2,6):
newurl = 'http://www.youdaili.net/Daili/QQ/31893_'+ str(i)+'.html'
findIP(newurl)
</code>

这样就把这个页面上的IP地址和端口都爬取了下来

爬取下来的IP地址需要处理一下,方便后面使用
<code>
ipdicts = []
for i in range(len(ipList)):
ipsignal = []
ipsignal.append(ipList[i][0])
ipsignal.append(serverList[i][0])
ipdicts.append(ipsignal)
print(len(ipdicts))
</code>

判断IP是否可用

<code>
import socket
socket.setdefaulttimeout(2)#设置最少反应时间
IPpool = []
for item in ipdicts:
proxy = item[0] + ':' +item[1]
proxy_host = "http://" + proxy#要改成"http://xxx.xxx.xxx.xxx:xxxx"的格式"
try:
proxy_handler = urllib.request.ProxyHandler({'http': proxy})
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)
html = urllib.request.urlopen('https://www.google.com.hk')
IPpool.append(proxy)
except Exception as e:
print(e)
</code>
这样可用的IP就存入到IPpool中了。

用Chrome使用代理IP打开网页

这里其实不需要用到Chrome,用urllib.request.urlopen()打开之后直接用BeautifulSoup解析就可以了。
这段代码只是提供了一个更有意思的玩法。
<code>
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy)
chrome = webdriver.Chrome(executable_path='C:\Python34\Scripts\chromedriver.exe',chrome_options=chrome_options)
chrome.get("https://www.google.com.hk")
chrome.close()
</code>

因为免费代理IP的质量实在捉急,所以这段代码用来刷点击率的话效率太低,只能用来练练手。

上一篇下一篇

猜你喜欢

热点阅读