记录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'});")