【问题标题】:Can't find element by id using selenium使用 selenium 无法通过 id 找到元素
【发布时间】:2017-07-23 17:55:26
【问题描述】:

我正在用 python 编写一个脚本,该脚本在网页 https://www.realtor.ca/ 上搜索特定位置。我的问题是在一开始。当你打开一个页面时,中间是一个很大的搜索元素。该元素的 HTML 是:

<input name="ctl00$elContent$ctl00$home_search_input"
 maxlength="255"  id="home_search_input" class="m_hme_srch_ipt_txtbox"
 type="text" style="display: none;">

我正在尝试使用 find_element_by_id 方法访问元素,但总是收到错误消息:消息:无法找到元素:[id="home_search_input"]

这是我的代码:

from selenium import webdriver as web
Url = "https://www.realtor.ca/"
browser = web.Firefox()
browser.get(Url)
TextField = browser.find_element_by_id("home_search_input")

有没有人遇到过类似的问题,或者有人知道如何解决吗?

【问题讨论】:

  • 那个网页上不存在的
  • @depperm 什么不存在?
  • ` 当你在中间打开一个页面是一个很大的搜索元素。该元素的 Html 是` .... 这不是该搜索的 html,因为它是隐藏的
  • style="display: none;" 指示元素不可见。在这种情况下,您需要弄清楚用户会做什么来启用此元素,以便您可以与之交互,然后编写步骤。

标签: python html python-3.x selenium selenium-webdriver


【解决方案1】:

导航到页面时,id 为 home_search_input 的元素一开始是不可见的。似乎只有在您单击“您在哪里”占位符(然后消失)后才能看到这个。您需要在测试中明确执行此操作。

此外,请确保使用隐式或显式等待语句,以确保您与之交互的元素被正确加载和呈现。

这是一个使用 Java 客户端绑定的页面示例 - Python 应该非常相似:

driver.get("https://www.realtor.ca/");

new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeClickable(By.id("m_hme_wherelooking_lnk"))).click();
driver.findElement(By.id("home_search_input")).sendKeys("demo");

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多