使用selenium找不到id的元素

时间:2017-03-03 14:53:26

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

我正在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")

有没有人遇到过类似的问题,或者有人知道如何修复它?

1 个答案:

答案 0 :(得分:3)

导航到页面时,标识为home_search_input的元素首先不可见。看来这个只有在你点击&#34;你在哪里看到&#34;占位符(然后消失)。您需要在测试中明确地执行此操作。

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

以下是使用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");
相关问题