selenium.common.异常.NoSuchElementException:消息:{“errorMessage”:“找不到id为'searchfacetcity'的元素”

2024-04-23 14:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python 3、Selenium和PhantomJS来浏览以下网站:

https://health.usnews.com/best-hospitals/search

我需要找到一个搜索字段并在其中输入文本,然后按enter键生成搜索结果。下面是与我要查找的搜索字段相对应的HTML:

<div class="search-field-view">

<div class="block-tight">
    <label class="" for="search-facet-city">
        <input id="search-facet-city" autocomplete="off" name="city" 
type="text" data-field-type="text" placeholder="City, State or ZIP" 
value="" />
    </label>
</div>

</div>

下面是我的python3代码,它试图使用id“search facet city”定位这个搜索字段

^{pr2}$

一旦文本输入搜索字段,我需要从页面中获取一些结果。但是,我一直得到一个NoSuchElementException错误;尽管搜索框元素确实存在,但它仍然无法找到它。我该怎么解决这个问题?在


Tags: texthttps文本dividcityfieldsearch
1条回答
网友
1楼 · 发布于 2024-04-23 14:32:42

我用Chrome试试这个:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys


url = 'https://health.usnews.com/best-hospitals/search'
location = 'Massachusetts'
# Instantiate the driver
driver = webdriver.Chrome(executable_path=r'/pathTo/chromedriver')
#driver = webdriver.PhantomJS(executable_path=r'/pathTo/phantomjs')
driver.get(url)
driver.maximize_window()
wait = WebDriverWait(driver, 20)
driver.save_screenshot('out.png');
elem=wait.until(EC.element_to_be_clickable((By.XPATH,"//div[@class='search-field-view']")))
span = elem.find_element_by_xpath("//span[@class='twitter-typeahead']")
input=span.find_element_by_xpath("//input[@class='tt-input' and @name='city']");
input.send_keys(location)
driver.save_screenshot('out2.png');

而且很管用。在

但是如果我尝试使用phantomJS,在driver.save_screenshot('out.png');中,我得到:

enter image description here

正如@JonhGordon在评论中所说,该网站做了一些检查。如果您想使用phantomJS,可以尝试更改desired_capabilities或{}。在

相关问题 更多 >