【问题标题】:How do I click an <a> tag with role=button using xpath?如何使用 xpath 单击带有角色 = 按钮的 <a> 标记?
【发布时间】:2021-03-17 10:06:10
【问题描述】:

我这里有一个 HTML 代码,它使用 &lt;a role='button'&gt; 标记作为按钮。

<li class="page">
  <a role="button" class="page-link" tabindex="0" aria-label="Page 2">2</a>
</li>

如何使用 selenium 和 xpath 使标签可点击?这是我到目前为止所拥有的,它似乎没有像我希望的那样执行点击。

       def nextPage(self):
            PATH = "C:\Program Files (x86)\ChromeDriver\chromedriver.exe"
            driver = webdriver.Chrome(PATH)

            link = 'https://seedly.sg/reviews/' + self.isp
            driver.get(link)
            time.sleep(2)

            driver.execute_script("window.scrollTo(0,3000)")
            nextButton = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, "//a[@role='button' and text()='2']"))
            )

            nextButton.click()
            nextButton.close()

【问题讨论】:

标签: python selenium xpath webdriver webdriverwait


【解决方案1】:

您必须滚动页面直到元素可见,然后才能单击 Helpfull link for scrool page

【讨论】:

    【解决方案2】:

    正如@Justin 所说,您需要滚动页面,以便您正在搜索的元素在页面上可见,然后单击该元素。

    driver.get("https://seedly.sg/reviews/sim-only-mobile-plans/m1");
    driver.execute_script("window.scrollTo(0,900)") #you can make an adjust 800 or 1000
    nextButton = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//a[@role='button' and text()='2']")))
    nextButton.click()
    

    为了使元素独一无二,我也更改了xpath

    【讨论】:

    • 嗯,它确实向下滚动到所需区域。但是,它仍然没有点击。我的浏览器只是自行关闭。不过感谢您的建议。
    • @user3195396 :我可以滚动点击。您必须检查窗口大小并使用限制 700/800/900/1000 并检查
    • @user3195396 :在driver.get()time.sleep(2) 之后的 nextButton 之后还有一个选项应该也可以工作。
    • 它似乎与 3000 配合得很好(这是正常的吗?),而浏览器不会自行关闭。无论如何,由于 ElementClickInterceptedException 错误“消息:元素点击被拦截:元素 2 在点 (333, 14) 处不可点击”,它仍然不可点击
    • 我没有遇到过这个问题。但是要摆脱拦截的问题,请使用 JavaScript 执行器单击下一步按钮。
    猜你喜欢
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 2014-05-19
    相关资源
    最近更新 更多