免费代理ip爬虫分享
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                免费代理ip爬虫分享
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                分享一個某代理網(wǎng)站的免費代理ip的爬蟲,直接復(fù)制到pycharm運行就可以了。
注意:爬取的代理ip有點坑,因為是免費的所以過期時間很快,可能1分鐘后就會失效。并且在scrapy使用這些代理ip還會給你打印一堆廣告。且用且珍惜。
import requests
from lxml import etree
import json
class XiciProxiesSpider(object):
    def __init__(self):
        self.start_url = 'http://www.xicidaili.com/nn'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'
        }
    def get_page_from_url(self, url):
        response = requests.get(url,headers=self.headers)
        return response.content.decode()
    def get_data_from_page(self, page):
        # print(page)
        # 把page轉(zhuǎn)換為Element對象
        html = etree.HTML(page)
        # 獲取包含代理信息的tr列表
        trs = html.xpath('//*[@id="ip_list"]/tr')[1:]
        # 遍歷trs, 獲取數(shù)據(jù)信息
        data = {
            'http':[],
            'https':[]
        }
        for tr in trs:
            try:
                ip = tr.xpath('./td[2]/text()')[0]
                port = tr.xpath('./td[3]/text()')[0]
                ip_type = tr.xpath('./td[6]/text()')[0].lower()
                # 如果ip不是http或https直接返回
                if ip_type not in data.keys():
                    return
                # 構(gòu)建代理數(shù)據(jù)
                item = {ip_type: '{}://{}:{}'.format(ip_type, ip, port)}
                # 檢查代理IP是否可用, 如果可用添加到列表中
                if self.validate_ip(item, ip_type):
                    print(item[ip_type])
                    data[ip_type].append(item[ip_type])
            except Exception as ex:
                print(ex)
                print(etree.tostring(tr))
        # print(data)
        return data
    def validate_ip(self, item, ip_type):
        try:
            test_url = "{}://baidu.com".format(ip_type)
            response = requests.get('http://baidu.com', proxies=item, timeout=2)
            if response.status_code == 200:
                return True
            return False
        except Exception as ex:
            return False
    def save_data(self, data):
        with open('proxies.json', 'w') as f:
            json.dump(data, f, indent=2)
    def run(self):
        # 獲取頁面內(nèi)寬容
        page = self.get_page_from_url(self.start_url)
        # 獲取可用代理IP
        data = self.get_data_from_page(page)
        # 保存數(shù)據(jù)
        self.save_data(data)
if __name__ == '__main__':
    fps = XiciProxiesSpider()
    fps.run()
                            總結(jié)
以上是生活随笔為你收集整理的免费代理ip爬虫分享的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: HTML-锚点
- 下一篇: eclipse启动了tomcat,但是浏
