Python脚手架系列-DrissionPage

记录DrissionPage模块使用中的一些常常复用的代码,持续更新…

接管谷歌浏览器

from DrissionPage import ChromiumPage, ChromiumOptions

co = ChromiumOptions().set_local_port(4249)
driver = ChromiumPage(addr_or_opts=co)

创建driver,如果浏览器已开启优先接管,需要设置谷歌浏览器的启动参数C:\Users\Gekte\AppData\Local\Google\Chrome\Application\chrome.exe --remote-debugging-port=4249 --remote-allow-origins=*设置端口需要对应。

获取tab

def get_tab(driver, html):
    tab_ids = driver.tab_ids
    for tab_id in tab_ids:
        this_tab = driver.get_tab(tab_id)
        if html in this_tab.url:
            return this_tab
    else:
        for tab_id in tab_ids:
            this_tab = driver.get_tab(tab_id)
            if this_tab.url in ["about:blank", "chrome://newtab/"]:
                return this_tab
    return driver.new_tab()

传入driver对象以及链接(支持链接的一部分),查找是不是有能复用的tab而无需创建新的。
如果需要获取多个tab对象,请使用下面的get_tabs函数防止重复获取

def get_tabs(driver, *urls):
    selectedTab = []
    tabs = []
    
    tab_ids = driver.tab_ids
    for url in urls:
        retTab = None
        
        for tab_id in tab_ids:
            this_tab = driver.get_tab(tab_id)
            if url in this_tab.url and this_tab not in selectedTab:
                retTab = this_tab
                break
        
        if not retTab:
            for tab_id in tab_ids:
                this_tab = driver.get_tab(tab_id)
                if this_tab.url in ["about:blank", "chrome://newtab/"] and this_tab not in selectedTab:
                    retTab = this_tab
                    break
        
        if not retTab:
            retTab = driver.new_tab()
        
        selectedTab.append(retTab)
        tabs.append(retTab)
    
    return tabs

# 使用 get_tabs 函数获取所有标签页
specTab, detailTab, manTab = get_tabs(driver, 'https://k.autohome.com.cn/spec/', 'https://k.autohome.com.cn/detail/', 'https://i.autohome.com.cn/')

chrome://newtab/对应谷歌新创建的页面,如果是其他浏览器请自行更换

执行Js代码

翻页到底部

driver.run_js("window.scrollTo({top: document.body.scrollHeight,behavior: 'smooth'});")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

d0ublecl1ck_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值