如何使用selenium python chromedri遍历多个url并在新选项卡中打开url

2024-05-23 14:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在循环中打开基于link_text找到的URL。下面是我尝试使用的程序。 实际上,发生了什么,实际上在那个页面上我有3次详细信息,有些时候会是4次(这是动态的)。在

更新代码:

from selenium.webdriver.support import ui
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(chrome_options=options, executable_path='C:\chromedriver_win32\chromedriver.exe')
driver.maximize_window()
driver.get("https://xxxxxx/blogs/")
if driver.find_element_by_xpath("(//span[@class='ui-datepicker-month'][contains(.,'May')])[1]"):        
    # get the number of details to click
    addr = driver.find_elements_by_link_text('Details')
    urls = [v.get_attribute("href") for v in addr]
    for x in range(1, len(urls) + 1):
        driver.execute_script("window.open();")
        driver.switch_to.window(driver.window_handles[x])
        driver.get(urls[x - 1])`

输出为:

它工作正常,在新选项卡中打开所有详细信息href。在

更新2: 根据Dmitri T代码,现在它正在工作打开所有细节href in new tabs:)谢谢帮助。最后一个我想尝试的是在datepicker循环中,我已经在5月份将日期硬编码为//span[@class='ui-datepicker-month'][contains(.,'May')])[1]"。我怎样才能循环通过这个,即点击每天的意思。点击5月1日,在每个newtab中打开所有“details”href,再次转到主url,5月2日单击,做同样的事情…在新标签页中打开所有“details”href…等等…我正在尝试编写代码…让你知道结果。谢谢各位专家。在


Tags: 代码fromimportuigetdriverseleniumdatepicker
2条回答

您应该能够使用下面的逻辑打开新选项卡中的所有详细信息链接。在

driver.get("https://xxxxxx/blogs/")
if driver.find_element_by_xpath("(//span[@class='ui-datepicker-month'][contains(.,'May')])[1]"):
    main_window = driver.current_window_handle
    # get the number of details to click
    addr = len(driver.find_elements_by_xpath("//a[@class='details'][contains(.,'Details')]"))
    # iterate through all the details links  (used the index rather elements list as it may lead to staleeleemnt exception after clicking on the first detiails link)
    for addrNum in range(addr):
        # get the details element based on index
        ele = driver.find_element_by_xpath("(//a[@class='details'][contains(.,'Details')])[" + str (addrNum+1) + "]")
        # get the href of the link
        href = ele.get_attribute('href')
        # open the href in another tab
        driver.execute_script("window.open('" + href +"');")
        # switching to parent window (on safer side)
        driver.switch_to.window(main_window)
  1. 使用For loop迭代来自addrlist的URL
  2. 使用get_attribute函数从web元素提取URL

假设以上提示,您需要修改代码,如:

addr = driver.find_elements_by_link_text('Details')
urls = [v.get_attribute("href") for v in addr]
for x in range(1, len(urls) + 1):
    driver.execute_script("window.open();")
    driver.switch_to.window(driver.window_handles[x])
    driver.get(urls[x - 1])

您可能还想考虑重新实现您的测试以使用Page Object pattern-这样,如果您将测试逻辑从UI部分分离出来,那么维护起来会更容易。在

相关问题 更多 >