2017-10-27 4 views
0

Python 3、Selenium、およびPhantomJSを使用して次のWebサイトをスクラップしようとしています。selenium.common.exceptions.NoSuchElementException:メッセージ:{"errorMessage": "id 'search-facet-city'の要素を見つけることができません。

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> 

は、ID使用して、この検索フィールドを見つけようと、私はPython 3のコードである「検索ファセット都市を。」

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エラーを受け取り続けます。それが存在するにもかかわらず、検索ボックス要素を見つけることができない。これをどうすれば解決できますか?

+0

あなたのポストのタイトルの誤差は_class_として「サーチ・ファセット都市」を探しているが、あなたの投稿コードが_ID_としてそれを探します。どちらですか? –

+0

申し訳ありませんが、それはタイプミスでした。それはidでなければなりません。 – rakeshb

+0

そのURLを取得しようとすると、私は '403 Forbidden'レスポンスを取得します。あなたはそれを読むことができるのですか? –

答えて

0

私はクロームでこれを試してみました:

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として

enter image description here

は、ウェブサイトは、いくつかのチェックを行い、コメントで述べています。あなたがphantomJSを使用する場合は、desired_capabilitiesservice_argsを変更しようとすることができます。

関連する問題