【问题标题】:Python Selenium Chrome loop through links in tabsPython Selenium Chrome 循环遍历选项卡中的链接
【发布时间】:2022-01-14 13:46:17
【问题描述】:

您好,我有一个主网页,它在主选项卡中打开以接受 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

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

谢谢。

【问题讨论】:

  • 但这不起作用:什么不起作用?
  • @undetectedSelenium 感谢您伸出援手,下面的答案是我需要的,我的问题是上面的代码不会打开和关闭选项卡 1,我用它来循环链接,以及始终保持打开状态的主标签(由于弹出 cookie)
  • 很高兴你有一个可行的解决方案,但我完全反对driver.window_handles[n]
  • @undetectedSelenium 到目前为止,我已经在这里使用了很多关于 selenium 的答案,如果您不介意写下您的建议,我将不胜感激。
  • 好的 :) 我会把它放在我的 ToDo 列表中

标签: python selenium selenium-chromedriver


【解决方案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])

【讨论】:

    猜你喜欢
    • 2018-07-20
    • 2018-07-06
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 2020-02-17
    相关资源
    最近更新 更多