【发布时间】: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,所以我认为我不会再次访问该页面。