搭建免费代理池

代理池搭建依赖数据库mongoDB
本文请求头UserAgent未提供
可以去这个网站找可用的复制

https://fake-useragent.herokuapp.com/browsers/0.1.11
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import pymongo
import threading
import aiohttp
import asyncio
import time
import random


# 存储
def insert_to_MongoDB(ip, score):
    if myCol.find_one({"IP": ip}) == None:  # 重复ip不存储
        myCol.insert_one({"IP": ip, "Score": score})


# 取出
def get_from_MongoDB(n=0):
    """
    :param n: 要返回的ip个数,默认为0取出全部
    :return:
    """
    r = myCol.find().sort("Score", -1).limit(n)
    return r


# 获取页面源码
def get_html(url):
     ua_list= [








           ]
    headers = {"User-Agent": random.choice( ua_list)}
    try:
        response = requests.get(url=url, headers=headers, timeout=5)
        if response.status_code == 200:
            return response.text
    except Exception:
        pass  # 获取源码失败
    # 如果不能访问,则使用ip池的代理ip进行尝试
    proxy_ips = get_from_MongoDB()
    for proxy_ip in proxy_ips:
        proxies = {"http": "http://" + proxy_ip["IP"], "https": "https://" + proxy_ip["IP"]}
        try:
            response_proxy = requests.get(url=url, headers=headers, proxies=proxies, timeout=5)
            if response_proxy.status_code == 200:
                return response_proxy.text
        except Exception:
            pass
    return ""  # 若所有代理均不能成功访问,则返回空字符串


# 西刺代理
def xicidaili():
    page = 3  # 要爬取的页数
    ip_list = []  # 临时存储爬取下来的ip
    for p in range(page + 1):
        url = "https://www.xicidaili.com/nn/" + str(p + 1)
        html = get_html(url)
        if html != "":
            soup = BeautifulSoup(html, 'lxml')
            ips = soup.find_all('tr', class_='odd')
            for i in ips:
                tmp = i.find_all('td')
                ip = tmp[1].text + ':' + tmp[2].text
                ip_list.append(ip)
                print('线程{}爬取ip:{}'.format(threading.current_thread().name, ip))
            time.sleep(3)
        else:
            print('西刺代理获取失败!')
            break
    for item in ip_list:
        queue_lock.acquire()
        insert_to_MongoDB(item, 10)
        queue_lock.release()


# 快代理
def kuaidaili():
    page = 10  # 要爬取的页数
    ip_list = []  # 临时存储爬取下来的ip
    for p in range(page + 1):
        url = "https://www.kuaidaili.com/free/inha/{}/".format(p + 1)
        html = get_html(url)
        if html != "":
            soup = BeautifulSoup(html, 'lxml')
            ips = soup.select('td[data-title="IP"]')
            ports = soup.select('td[data-title="PORT"]')
            for i in range(len(ips)):
                ip = ips[i].text + ':' + ports[i].text
                ip_list.append(ip)
                print('线程{}爬取ip:{}'.format(threading.current_thread().name, ip))
            time.sleep(3)
        else:
            print('快代理获取失败!')
            break
    for item in ip_list:
        queue_lock.acquire()
        insert_to_MongoDB(item, 10)
        queue_lock.release()


# 评分调整
def adjust_score(ip, myType):
    """
    验证成功的直接评分变为100,未验证成功的减1,评分为0的直接删除
    :param ip:
    :param type: 1 加分,-1 减分
    :return:
    """
    if myType == 1:
        query_ip = {"IP": ip}
        new_value = {"$set": {"Score": 100}}
        myCol.update_one(query_ip, new_value)
    elif myType == -1:
        query_ip = {"IP": ip}
        current_score = myCol.find_one(query_ip)["Score"]
        if current_score == 1:
            myCol.delete_one(query_ip)
        else:
            new_value = {"$set": {"Score": current_score - 1}}
            myCol.update_one(query_ip, new_value)


async def ip_test(url, headers, proxy):
    test_proxy = "http://" + proxy
    conn = aiohttp.TCPConnector(verify_ssl=False)
    async with aiohttp.ClientSession(connector=conn) as session:
        try:
            async with session.get(url=url, headers=headers, proxy=test_proxy) as resp:
                if resp.status == 200:
                    adjust_score(proxy, 1)
                else:
                    adjust_score(proxy, -1)
        except:
            adjust_score(proxy, -1)


# ip池测试
def pool_test():
    COUNTS = 100  # 每次测试100个ip
    # ua = UserAgent()
    ua_list =
     [






    ]
    proxy_ips = list(get_from_MongoDB())
    test_url = "https://m.maoyan.com/"  # 可替换为要爬取的网址
    for i in range(0, len(proxy_ips), COUNTS):
        tasks = [ip_test(test_url, {"User-Agent": random.choice( ua_list)}, proxy["IP"]) for proxy in
                 proxy_ips[i:i + COUNTS]]
        loop = asyncio.get_event_loop()
        loop.run_until_complete(asyncio.wait(tasks))
        print("共{}个,已测试{}个".format(len(proxy_ips) + 1, COUNTS + i))
        time.sleep(3)


# 爬取代理ip线程启动
def crawler_start(proxy_dict):
    global threads
    for proxy in proxy_dict.keys():
        thread = threading.Thread(target=proxy_dict[proxy], name=proxy)
        thread.start()
        threads.append(thread)
    for t in threads:  # 等待所有线程完成
        t.join()


if __name__ == '__main__':
    # 连接MongoDB数据库
    myClient = pymongo.MongoClient("mongodb://localhost:27017/")
    myDB = myClient["IPpool"]
    myCol = myDB["pool"]

    # 伪装用户代理
    ua_list = [




           ]
    ua = random.choice( ua_list)

    # 间隔5分钟爬取和测试一次
    while 1:
        # 爬取模块线程
        queue_lock = threading.Lock()
        threads = []
        proxy_dict = {"kuaidaili": kuaidaili, "xicidaili": xicidaili}
        crawler_start(proxy_dict)

        # 测试模块线程
        print("代理ip爬取完毕,开始进行测试!")
        pool_test()
        print("测试完毕!")
        time.sleep(300)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
搭建Selenium IP代理,你可以按照以下步骤进行操作: 1. 首先,你需要安装selenium-wire模块。你可以使用以下命令在终端中安装该模块: ```pip install selenium-wire``` 2. 接下来,你需要导入所需的包和模块。例如,你可以导入selenium、fake_useragent和selenium.webdriver.chrome.options模块。 ``` from selenium import webdriver from fake_useragent import UserAgent from selenium.webdriver.chrome.options import Options ``` 3. 设置代理服务器的配置和用户代理头。你可以使用ChromeOptions()来设置代理服务器和添加用户代理头。 ``` ops = Options() headers = {'User-Agent': UserAgent().random} ``` 4. 创建一个WebDriver实例,并使用指定的驱动程序路径来初始化。例如,你可以使用webdriver.Chrome()来创建一个Chrome浏览器的实例。 ``` driver = webdriver.Chrome(r'D:\360安全浏览器下载\chromedriver.exe') ``` 5. 获取代理IP地址并将其添加到代理服务器中。你可以使用webdriver的get()方法来打开代理IP地址的网页,并使用find_element_by_xpath()方法来获取代理IP地址的文本。然后,你可以使用add_argument()方法将代理IP地址添加到ChromeOptions中的代理服务器选项中。 ``` api_url = '让你复制的代理api链接' driver.get(api_url) a = driver.find_element_by_xpath('/html/body/pre').text # 获取代理 ops.add_argument('--proxy-server=http://%s' % a) # 添加代理 ``` 6. 清除浏览器的cookies。你可以使用delete_all_cookies()方法来清除浏览器的cookies。 ``` driver.delete_all_cookies() # 清除cookies ``` 7. 打开你想要使用代理IP访问的网页,并执行你需要的操作。例如,你可以使用get()方法打开淘宝网并在搜索框中输入关键字。 ``` driver.get('https://www.taobao.com/') driver.find_element_by_name('q').send_keys('华为手机') ``` 请注意,上述代码仅供参考,你需要根据自己的实际情况进行适当的修改和调整。确保你已经正确安装了selenium-wire模块,并且已经下载和配置了Chrome驱动程序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [selenium使用代理IP](https://blog.csdn.net/weixin_46211269/article/details/123251070)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值