寫爬蟲程序時,爲了使爬蟲不被屏蔽,有時需要使用到代理IP,這時就要去免費的代理IP網站找IP,爲了省事,我寫了個爬蟲程序,把代理IP網站的所有IP全部爬了下來,存在本地的文件裏,以後需要直接從文件中讀取。
這個網頁的內容比較容易抓取,我主要需要三個內容,http類型,IP地址和端口號
以下是源碼:
#!/usr/bin/python
# -*- encoding:utf-8 -*-
"""
@author : kelvin
@file : scrapy01
@time : 2017/2/20 22:49
@description :
"""
import requests, re
from bs4 import BeautifulSoup
headers = {
""
}
response = requests.get("http://www.xicidaili.com/nn", headers=headers) # 添加header僞裝成爲瀏覽器
print response
# 一種匹配方法
# pattern = re.compile("(\d{1,3}\.){3}\d{1,3}")
# for td in soup.find_all('td'):
# text = td.text
# if text:
# r = pattern.match(text)
# if r:
# print r.group()
def scrap_ip(html_soup): # 提取單頁的結果
# 存到字典中遍歷
result = []
for tr in html_soup.find_all("tr"):
for td in tr.findAll('td'):
result.append(td.text)
n = 0
ip_result = []
for x in range(len(result)):
ip_result.append(result[5+n]+','+result[1+n] + ":" + result[2+n]) # IP地址在第二個td,端口號在第三個td,協議形式在第六個td
n += 10 # 每個tr塊中有10個td
if n+1 > len(result): # 避免list index out of range
break
return ip_result
# 正則匹配
# proxies = soup.find_all(text=re.compile("(\d{1,3}\.){3}\d{1,3}"))
def scrapy_proxy(page_rank): # 循環抓取多個頁面
ip_result = []
for page in range(1, page_rank):
response = requests.get("http://www.xicidaili.com/nn/%d" % page, headers=headers)
print response
soup = BeautifulSoup(response.text, 'lxml')
ip_in_page = scrap_ip(soup)
ip_result.append(ip_in_page) # 結果嵌套存入字典
return ip_result
ip_result = scrapy_proxy(2)
print ip_result
with open('proxies.txt', 'w') as f:
for proxies in ip_result: # 每一頁的代理IP
for proxy in proxies: # 每一頁裏面每一個IP
f.writelines(proxy+"\n")