Python Selenium Chrome 循环浏览选项卡中的链接

标签 python selenium selenium-chromedriver

您好,我有一个主网页,在主选项卡中打开以接受 cookie,其余链接应在选项卡中循环打开和关闭:

links = ['https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/']

driver = webdriver.Chrome(executable_path=r'C:\ProgramFiles(x86)\chromedriver.exe')
driver.get('https://www.deviceinfo.me/') #open the main tab

for link in links: 
    driver.execute_script("window.open();") # open a new tab
    driver.switch_to.window(driver.window_handles[1])   # switch to the tab 1
    driver.get(link)
    driver.close() # close tab 1

但这不起作用,有什么建议如何解决这个问题吗?

谢谢。

最佳答案

这应该有效:

您基本上到达了 window_handle[1],但没有切换回父窗口,因此出现了问题

links = ['https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/']

driver = webdriver.Chrome(executable_path=r'C:\ProgramFiles(x86)\chromedriver.exe')
driver.get('https://www.deviceinfo.me/') #open the main tab

for link in links: 
    driver.execute_script("window.open();") # open a new tab
    driver.switch_to.window(driver.window_handles[1])   # switch to the tab 1
    driver.get(link)
    driver.close() # close tab 1
    driver.switch_to.window(driver.window_handles[0])

关于Python Selenium Chrome 循环浏览选项卡中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70711550/

相关文章:

python - 安装IbPy以在spyder(anaconda)中使用

python - 如何使用Python从网页下载所有图像?

python - 在 Selenium Chromedriver、Python 中禁用 CSS 和图像

javascript - 代码在 javascript 中工作正常,但在 selenium 中则不行

Python 正则表达式没有给出预期的结果

python - flask-wtf 表单验证不适用于我的新应用

python - 编写脚本从网站下载文件? (Python、 Selenium (?))

java - 在java中使用selenium包含或上传文件

c# - 仅在远程运行时通过 Selenium 测试中途抛出 WebDriverException

python - 在 matplotlib 中,如何绘制从轴向外指向的 R 样式轴刻度?