【问题标题】:Python Selenium - how to click dynamic generated href page linksPython Selenium - 如何点击动态生成的href页面链接
【发布时间】:2021-09-07 03:50:52
【问题描述】:

我正在使用 selenium 和 python 自动化一个过程。但我被一些东西困住了。我必须单击使用硒的链接。这个链接是href,每次都会动态生成。 href 链接类似于 3。对于另一个页面,它将是 66

现在,模拟点击这个链接,有什么方法可以点击吗?如何获取动态生成的链接?我正在为 selenium webdriver 使用 python 代码。

示例尝试“self.driver.find_element(By.CSS_SELECTOR, "create_job_listing_ajax > div:nth-child(4) > div > div > div:nth-child(2) > center > a").click()//将 URL 复制为 xpath

【问题讨论】:

  • 尽可能分享 URL 或 HTML,您尝试过的代码和错误。
  • 请提供网站链接。
  • 我们的 API 正在开发中,尚未发布。我们在本地环境中运行 selenium 脚本。我会分享HTML代码以供参考,
    1
    xyz 匹配
  • 代码尝试:self.driver.find_element_by_xpath("//*[contains(@href,'xyz match')]").click() 并且错误是“2021-09-07 10: 38:06,089 消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//*[contains(@href,'xyz match')]"} "
  • 根据您使用的 CSS 选择器,看起来 a 在几个 div 标记内。尝试使用它来跟踪 a 标记。像这样xpath - //div[...]//a

标签: python api selenium automation selenium-webdriver-python


【解决方案1】:

你写的很漂亮,写的更轻松!

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#create_job_listing_ajax > div:nth-child(4) > div > div > div:nth-child(2) > center > a'))).click()

self.browser.find_element_by_css_selector('#create_job_listing_ajax > div:nth-child(4) > div > div > div:nth-child(2) > center > a').click()

【讨论】:

【解决方案2】:

由于我们没有enough HTML 来正确提供working xpath 或任何其他locater,因此最好的方法是使用below xpath.

//div[@class='col']/center[@class='center_tag']/a

看看我们到底能到达a tag,它有一个动态生成的href属性。

现在您应该始终检查 HTML DOM。

检查步骤:

Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste  and see `//div[@class='col']/center[@class='center_tag']/a` is getting highlighted or not. 

我们还必须确保我们不会使用该 xpath 获得多个节点。检查最右边我们有多少条目?应该是 1/1 才能使它工作。

代码:

self.driver.find_element(By.XPATH, "//div[@class='col']/center[@class='center_tag']/a").click()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2021-12-03
    相关资源
    最近更新 更多