首页 > 其他分享 >爬虫自动化之drissionpage实现随时切换代理ip

爬虫自动化之drissionpage实现随时切换代理ip

时间:2024-04-29 12:00:58浏览次数:15  
标签:drissionpage get ip 爬虫 tab text co browser

爬虫自动化之drissionpage实现随时切换代理ip

https://blog.csdn.net/qq_32334103/article/details/126133862

下载 SwitchyOmega地址: https://github.com/FelisCatus/SwitchyOmega/releases

 

 

import platform

from DrissionPage import ChromiumPage, ChromiumOptions
from loguru import logger


def get_free_ip():
    url = "https://www.zdaye.com/free/?ip=&adr=&checktime=&sleep=&cunhuo=&dengji=1&nadr=&https=&yys=&post=&px="
    browser.get(url, retry=3, interval=1, timeout=15)
    ip_ports = []
    for tr in browser.eles('x://table[@id="ipc"]//tr')[1:]:
        tds = [td.text for td in tr.eles("x://td")]
        ip_ports.append((f"{tds[0]}:{tds[1]}", tds[3]))
    print(len(ip_ports), ip_ports)
    return ip_ports


def switch_ip(ip_port=None):
    global set_proxy
    if ip_port:
        # 设置proxy
        ip, port = ip_port.split(":")
        tab = browser.new_tab()
        tab.get("chrome-extension://padekgcemlokbadohgkifijomclgjgif/options.html#!/profile/proxy")
        tab.ele('x://input[@ng-model="proxyEditors[scheme].host"]').input(ip, clear=True)
        tab.ele('x://input[@ng-model="proxyEditors[scheme].port"]').input(port, clear=True)
        tab.ele('x://a[@ng-click="applyOptions()"]').click()
        tab.wait(1)
        # 提示框
        txt = tab.handle_alert()
        print("提示框", txt)
        tab.handle_alert(accept=False)
        if not omega_proxy:
            # 切换proxy
            tab.get("chrome-extension://padekgcemlokbadohgkifijomclgjgif/popup/index.html#")
            tab.wait(1)
            tab.ele('x://span[text()="proxy"]').click()
            set_proxy = True
    else:
        tab = browser.new_tab()
        tab.get("chrome-extension://padekgcemlokbadohgkifijomclgjgif/popup/index.html#")
        tab.ele('x://span[text()="[直接连接]"]').click()
    if len(browser.tab_ids) > 1:
        print("当前tab个数", len(browser.tab_ids))
        tab.close()


if platform.system().lower() == 'windows':
    co = ChromiumOptions()  # .set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
else:
    co = ChromiumOptions().set_paths(browser_path=r"/opt/google/chrome/google-chrome")
    co.headless(True)  # 设置无头加载  无头模式是一种在浏览器没有界面的情况下运行的模式,它可以提高浏览器的性能和加载速
    # co.incognito(True)  # 无痕隐身模式打开的话,不会记住你的网站账号密码的
    co.set_argument('--no-sandbox')  # 禁用沙箱 禁用沙箱可以避免浏览器在加载页面时进行安全检查,从而提高加载速度 默认情况下,所有Chrome 用户都启用了隐私沙盒选项  https://zhuanlan.zhihu.com/p/475639754
    co.set_argument("--disable-gpu")  # 禁用GPU加速可以避免浏览器在加载页面时使用过多的计算资源,从而提高加载速度
    co.set_user_agent(user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36')  # 设置ua

co.set_timeouts(6, 6, 6)
co.set_local_port(9211)
# 1、设置switchyOmega插件
co.add_extension(r'C:\Users\Ad\Desktop\proxy_switchyomega-2.5.20')
browser = ChromiumPage(co)

# 2、重置switchyOmega插件
omega_proxy = False
switch_ip()
browser.get("https://www.ip138.com/", retry=0)
html_text = browser.get_frame('x://div[@class="hd"]//iframe').ele('text:您的iP地址是').text
logger.success(f">>>>当前的ip {html_text}")

# 3、随机切换代理ip
# ip_all = get_free_ip()
ip_all = [{"ip": "10.1.3.56", "port": 7890, "expire_time": "2024-04-27 22:24:00"}]
for ips in ip_all:
    logger.info(f"~~~切换ip,now {ips['ip']}")
    # 重置switchyOmega插件
    switch_ip(f"{ips['ip']}:{ips['port']}")
    browser.wait(1)
    try:
        browser.get("https://www.baidu.com/", retry=0)
        browser.get("https://www.ip138.com/", retry=0)
        browser.get("https://www.google.com/", retry=0)
        html_text = browser.get_frame('x://div[@class="hd"]//iframe').ele('text:您的iP地址是').text
        logger.success(f">>>>>>>>切换代理成功 {html_text}")
    except Exception as err:
        logger.error(f"----------切换代理失败 dp {err}")
    browser.wait(10)
browser.quit()

  

  

标签:drissionpage,get,ip,爬虫,tab,text,co,browser
From: https://www.cnblogs.com/yoyo1216/p/18165380

相关文章

  • PHP 使用CURL库IP欺骗,隐藏真实客户端IP
    首先搭建环境,建立个ip.php.代码如下:<?error_reporting(0);functionGetIP(){if($_SERVER['HTTP_CLIENT_IP']){$onlineip=$_SERVER['HTTP_CLIENT_IP'];}elseif($_SERVER['HTTP_X_FORWARDED_FOR']){$onlineip=$_SERVER['HTTP_X_......
  • ddddocr 文字验证码识别库 pip install下载失败
    第三方开源库,验证码识别github地址:https://github.com/sml2h3/ddddocr安装pipinstallddddocr下载失败的话使用国内安装源pip3install-ihttps://pypi.tuna.tsinghua.edu.cn/simpleddddocr附带一个api快速部署github地址:https://github.com/sml2h3/ocr_api_server......
  • JavaScript: FullScreen
     <!doctypehtml><html><head><metacharset="utf-8"> <metaname="viewport"content="width=device-width,initial-scale=1.0"> <metacontent="text/html;charset=utf-8"http-equiv=&......
  • 为什么我反对过度使用TypeScript?
    前言在2024年,TypeScript肯定算不上什么新鲜的技术.但是经过长时间的使用,我认为可以使用,但是要适度.类型跟不上业务的变化我们知道TypeScript的类型定义是业务的体现.但是业务的变化在很多公司都是非常快的.在产品功能上可能更改了一点点类型定义,但是你的类型系统可......
  • IPC-7711/21D, IPC-7711D, IPC-7721D 电子组件的返工、修改和维修,验收标准。Rework,
    IPC-7711/21-RevisionD-StandardOnly:Rework,ModificationandRepairofElectronicAssembliesTheIPC-7711/21guideprovidesproceduresforrework,repairandmodificationofprintedboardassemblies,includingtoolsandmaterials,commonprocedures,......
  • IPC最新发行了新标准:IPC-A-610J, IPC-J-STD-001J, IPC-7711/21D, IPC-2221C
    IPC最新发行了新标准:IPC-A-610J,IPC-J-STD-001J,IPC-7711/21D,IPC-2221C  2024年伊始,IPC又更新了一些新的标准,大家可以及时去更新了。IPC-A-610J_EN2024TOCAcceptabilityofElectronicAssemblies大家对这个标准都不陌生了吧,从事电子行业的技术......
  • yum安装mysql报错--您可以尝试添加 --skip-broken 选项来解决该问题 清除缓存命令
    yum安装mysql报错--您可以尝试添加--skip-broken选项来解决该问题    安装mysql时,如果安装报错,首先删除缓存,    1、清除缓存  yumcleancache    2、重新加载  yummakecache    3、重新安装  yuminstallmysql    此......
  • 树莓派怎么设置固定IP地址
    参考https://blog.csdn.net/ByteBox/article/details/134752264修改配置文件/etc/dhcpcd.conf修改以下配置,其余配置保存不变本次修改的是无线网卡wlan0interfacewlan0staticip_address=192.168.4.212/24staticrouters=192.168.4.1staticdomain_name_servers=192.16......
  • JavaScript流程控制语句
    JavaScript流程控制语句在一个程序执行的过程中,各条语句的执行顺序对程序的结果是有直接影响的。所以,我们必须清楚每条语句的执行流程。而且,很多时候我们要通过控制语句的执行顺序来实现我们想要的业务逻辑和功能。分类一般我们把流程控制语句分为以下三类顺序结构选择结......
  • k8s kube-proxy 负载均衡路由策略 IPVS 为什么iptables 更高效
    环境lsb_release-aNoLSBmodulesareavailable.DistributorID: UbuntuDescription: Ubuntu24.04LTSRelease: 24.04Codename: noble先说原理iptables如果服务过多或者pod过多就要则添加海量的iptabes规则iptables使用的具体算法主要是线性搜索,也可以称为顺......