Python爬虫实战——代理IP全部抓取

写爬虫程序时,为了使爬虫不被屏蔽,有时需要使用到代理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")

结果图:



  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值