Python之免费代理ip的抓取与使用

这篇博客讲述了如何使用Python从网站抓取免费代理IP,进行有效性测试,并将结果存储到MongoDB。作者提到大部分免费IP不可用,且计划改进为多线程或多进程以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python之免费代理ip的抓取与使用

  • 使用爬虫不可避免的就会遇到网站的各种封ip操作,因此就需要我们找寻代理,通过代理进行操作,屏蔽自己真实ip。
  • 本文直接从网站中抓取代理ip地址,进行测试,并将测试的结果直接输出到MongoDB中,最后可实现去重操作
  • 这里测试ip应该改成多线程才合适,但是目前我还不会,所以先这么着了,测试慢了点
  • 核心字段在于html = requests.get(url=url, headers=headers, proxies=proxy_ip),request中proxies字段的使用。
    测试截图如下:
import requests
import pymongo
from lxml.html import etree


class SelfIpProxy():
    def __init__(self):  # 设置区域
        self.depth = 1
        self.timeout = 10
        self.collection = pymongo.MongoClient()['Proxies']['free2']
        self.url = {
   
   'http':"http://19ncc.medmeeting.org/cn",'https':"https://www.baidu.com"}
        self.headers = {
   
   
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
            'Referer': 'https://www.xicidaili.com/nn/2'}

    def get_ip(self):  # 从网站获取ip
        urls = [
            'https://www.xicidaili.com/nn/{}'.format(i) for i in range(1, self.depth + 1)]
        for url in urls:
            html = requests.get(url, headers=self.headers, timeout=30)
            html.encoding = 'utf-8'
            e_html = etree.HTML(html.text)
            ips = e_html.xpath('//table[@id="ip_list"]/tr/td[2]/text()')
            ports = e_html.xpath('//table[@id="ip_list"]/tr/td[3]/text()')
            modes = e_html.xpath('//table[@id="ip_list"]/tr/td[6]/text()')
            for ip, port, mode in zip(ips, ports, modes):
                item = dict()
                item
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值