2016-10-21 13 views
1

http://www.emoryhealthcare.org/locations/offices/advanced-digestive-care-1.htmlから情報をスクラップしようとしています。BeautifulSoupがすべての要素をプルしない

「消化器」と「内科」のページの下3分の1に表示される専門医を掻き集めたいと思います。要素を調べると、li<div class="module bordered specialist">であることがわかりましたが、スープをループして見つけた各項目を印刷しようとすると、予想外の結果が返されます。

<div class="module bordered specialist"> 
<ul> 
<li>Cardiac Care</li> 
<li>Transplantation</li> 
<li>Cancer Care (Oncology)</li> 
<li>Diagnostic Radiology</li> 
<li>Neurosciences</li> 
<li>Mental Health Services</li> 
</ul> 
</div> 

ブラウザでウェブサイトを開くと、コンテンツが予期される結果に切り替わる前に、上記の値が点滅することがわかります。私が意図しているアイテムをこすってしまう可能性を改善する方法はありますか?

+0

ページの読み込み後にコンテンツを変更するjavascriptがあるようです。 –

+1

'selenium'を使用して数秒待つことができます(変更にかかる時間はどれくらいですか)。 –

答えて

3

セレンを使用して数秒待ってから、以前と同じように解析してください。それはトリックを行うように見えた。

from selenium import webdriver 
import os 
import time 
from bs4 import BeautifulSoup 

chromedriver = "/Users/Rafael/chromedriver" 
os.environ["webdriver.chrome.driver"] = chromedriver 
driver = webdriver.Chrome(chromedriver) 
driver.get('http://www.emoryhealthcare.org/locations/offices/advanced-digestive-care-1.html') 
time.sleep(5) 
html = driver.page_source 

soup = BeautifulSoup(html, 'lxml') 
results = soup.find_all("div", { "class" : "module bordered specialist" }) 
print(results[0].text) #prints GastroenterologyInternal Medicine 
+0

ああ、セレンと' time.sleep'はページを解析する前にロードを完了できるようにしますか? – Daniel

+0

ええ、それはアイデアです、特定の要素が読み込まれるのを待ってよりエレガントな方法がありますが、このサイトはかなり安定しているようです –

0

あなたは、単純なPOSTリクエストがデータを取得することができ、セレンを必要としない:

enter image description here

だから、あなたが必要なのは、その要求を模倣することです:

import requests 

# you can change there fields to get different results 
data = {"selectFields":["Name","URL","Specialists"],"filters":{},"orderBy":{"Name":-1}} 

post = "http://www.emoryhealthcare.org/service/findPhysician/api/locations/retrieve" 
# post the data as json and create a dict from the returned json. 
js = requests.post(post, json=data).json() 
print(js[u'locations'][0][u'Specialists']) 

どの実行すると、あなたには:

In [3]: import requests 
...: 
...: data = {"selectFields":["Name","URL","Specialists"],"filters":{},"orderB 
...: y":{"Name":-1}} 
...: post = "http://www.emoryhealthcare.org/service/findPhysician/api/locatio 
...: ns/retrieve" 
...: js = requests.post(post, json=data).json() 
...: print(js[u'locations'][0][u'Specialists']) 
...: 
[u'Gastroenterology', u'Internal Medicine'] 

jsonには多数のデータがありますが、おそらくあなたが望むものはそこにあります。

関連する問題