【问题标题】:selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":"Unable to find element with id 'search-facet-city'"selenium.common.exceptions.NoSuchElementException:消息:{“errorMessage”:“无法找到 id 为'search-facet-city'的元素”
【发布时间】:2017-10-27 01:49:15
【问题描述】:

我正在尝试使用 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>

下面是我的 Python 3 代码,它尝试使用 ID“search-facet-city”来定位这个搜索字段。

def scrape(self):
    url = 'https://health.usnews.com/best-hospitals/search'
    location = 'Massachusetts'

    # Instantiate the driver
    driver = webdriver.PhantomJS()
    driver.get(url)
    driver.maximize_window()
    driver.implicitly_wait(10)

    elem = driver.find_element_by_id("search-facet-city")
    elem.send_keys(self.location)

    driver.close()

将文本输入搜索字段后,我需要从页面中抓取一些结果。但是,我不断收到 NoSuchElementException 错误;尽管它存在,但它无法找到搜索框元素。我该如何解决这个问题?

【问题讨论】:

  • 您的帖子标题中的错误是将“search-facet-city”作为 class 查找,但您发布的代码将其查找为 id我>。是哪个?
  • 抱歉,打错了。应该是 id。
  • 当我尝试获取该 url 时,我收到了 403 Forbidden 响应。你确定你能看懂吗?
  • 是的,我可以阅读网址。我可以从 url 中抓取一些文本,但我的主要问题是找到搜索框并在其中输入文本。我不太确定是什么导致了 403 Forbidden 响应。您是否包含了所有必需的导入?
  • 我在命令行上从wget 获取 403。该网站可能不允许使用机器人类型的客户端。我尝试了 chrome 中的 url 并加载了页面,但是当我尝试查看源代码时它完全冻结了我的 Mac,所以我认为我不会再次访问该页面。

标签: python selenium phantomjs


【解决方案1】:

我用 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'); 中获得:

正如@JonhGordon 在cmets 中所说,该网站进行了一些检查。如果您想使用 phantomJS,您可以尝试更改 desired_capabilitiesservice_args

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多