【问题标题】:Click method not working - using selenium webdriver with java单击方法不起作用 - 将 selenium webdriver 与 java 一起使用
【发布时间】:2021-01-13 11:43:45
【问题描述】:

我正在尝试从公共网站上抓取数据。 在搜索页面输入搜索值并按下查看按钮(正常提交)它会显示结果。

正常浏览器视图按钮单击并按预期显示报告。但是当我尝试通过 Webdriver 代码单击相同的按钮时,该按钮会单击但未显示结果。

任何人都可以面对这个问题吗?

我尝试使用 XPath(//*[@id="b-form-submit"]/div/button) 使用以下方法单击按钮

Click()
Submit()
Click using Javascript
Click using action class (keyboard event)

按钮 HTML 代码

<div class="b-button" id="b-form-submit">
   <div class="b-button-container">
      <span class="left">
      <i></i>
      </span>
      <button alt="View" type="submit">View</button>
      <span class="right">
      <i></i>
      </span>
   </div>
</div>

当我尝试从 webdriver(调试模式)手动单击查看按钮时,它不是 wokring,而是与正常工作的 web 浏览器(所有浏览器)相同

【问题讨论】:

  • 您的网页是否公开?可能是网站阻止了网络抓取。
  • @KunduK - 是的,它是一个公共网页。如何阻止网络抓取?我可以通过 URL 浏览网页,也可以输入搜索值
  • 您能否Edit您的帖子并更新网址,以便其他贡献者可以帮助您。
  • @KunduK - 抱歉,出于安全原因,我无法分享网址。
  • 尝试显式等待并检查它是否有效。 new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[text()='View']"))).click();

标签: javascript java selenium selenium-webdriver


【解决方案1】:

&lt;button&gt; 不是 &lt;div&gt; 的直接后代,您可以使用以下任一 Locator Strategies::

  • css_selectors:

    div#b-form-submit>div button[alt='View']
    
  • xpath:

    //div[@id="b-form-submit"]/div//button[@alt='View' and text()='View']
    

所以在元素上的click(),文本为View,您可以使用以下Locator Strategies

  • cssSelector:

    driver.findElement(By.cssSelector("div#b-form-submit>div button[alt='View']")).click();
    
  • xpath:

    driver.findElement(By.xpath("//div[@id="b-form-submit"]/div//button[@alt='View' and text()='View']")).click();
    

理想情况下,click() 在您需要为elementToBeClickable() 诱导WebDriverWait 的元素上,您可以使用以下任一Locator Strategies

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#b-form-submit>div button[alt='View']"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id="b-form-submit"]/div//button[@alt='View' and text()='View']"))).click();
    

【讨论】:

  • 我的 XPath 没有任何异常,而且您的 XPath 也正确。我打开驱动程序EXE在该驱动程序中手动加载网页并单击查看按钮它不显示结果,同时我可以输入搜索值。
  • @Prabu 查看更新的答案并告诉我状态。
  • XPath 中没有问题。按钮在驱动程序中单击,但没有产生结果,我认为该站点通过驱动程序执行阻止了搜索结果。
  • @Prabu 我们不了解该站点,也不确定是否检测到该机器人。你能根据你的新要求提出一个新问题吗? Stackoverflow 贡献者将很乐意为您提供帮助。
  • 谢谢 请参考我的新问题stackoverflow.com/questions/65774494/…
猜你喜欢
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2017-08-18
  • 1970-01-01
相关资源
最近更新 更多