首页 > 解决方案 > Python Selenium Loop 点击链接

问题描述

我无法循环单击链接。当我尝试循环单击链接时,它只会单击第一个链接。

从 html 代码中,我还需要名为“key”值的元素。如何捕捉它。

将 html 文件复制到 Dropbox 中。请点击https://www.dropbox.com/sh/85rx13m8iqwax4b/AACNDq_YyOukLh22JNv76vjua?dl=0

html代码

https://pastebin.com/Cyg98W2C

我试过的Python代码

elem = WebDriverWait(browser, 200).until(EC.element_to_be_clickable((By.XPATH, "//DIV[@id='propertySummaryList']/DIV[@class='summaryListItem   ']/DIV[1]/DIV[3]/DIV[1]/H2[1]/A[1]")))
     elem.click()
     browser.back()

编辑:添加了保管箱链接。由于该网站仅登录。我已经制作了该页面的副本。

标签: pythonseleniumselenium-chromedriver

解决方案


您可以收集所有元素,然后使用相对查找来查找您需要的链接。请注意,如果您不在新窗口中打开点击,这可能会导致元素过时。

summaryList = driver.find_elements_by_xpath("//DIV[@id='propertySummaryList']/DIV[@class='summaryListItem   ']")
for elements in summaryList:
    link = elements.find_elements_by_xpath(".//h2//a")
    link.text // or link.click() but need to open in a new window or will get staleElementReference

推荐阅读