2015-04-04 97 views
1

我想首先說我在這個網站上回顧了幾個解決方案,但似乎沒有一個適合我。Python中的BeautifulSoup - DIV內容不顯示

我只是試圖從本網站訪問div標籤的內容:https://play.spotify.com/chart/3S3GshZPn5WzysgDvfTywr,但內容未顯示。

這裏是我的代碼至今:

SpotifyGlobViralurl='https://play.spotify.com/chart/3S3GshZPn5WzysgDvfTywr' 
browser.get(SpotifyGlobViralurl) 
page = browser.page_source 
soup = BeautifulSoup(page) 
#the div contents exist in an iframe, so now we call the iframe contents of the 3rd iframe on page: 
iFrames=[] 
iframexx = soup.find_all('iframe') 
response = urllib2.urlopen(iframexx[3].attrs['src']) 
iframe_soup = BeautifulSoup(response) 
divcontents = iframe_soup.find('div', id='main-container') 

我想拉「主容器」 DIV,但是你會看到,它顯示爲空的內容存儲在divcontent變量時創建。但是,如果您訪問實際的URL並檢查元素,您會發現這個「main-container」div聲明充滿了它的所有內容。

我很感激幫助。

回答

0

這是因爲它的容器是動態加載的。我注意到你正在使用selenium,你必須繼續使用它,切換到iframe和等待main-container加載

wait = WebDriverWait(browser, 10) 

# wait for iframe to become visible 
iframe = wait.until(EC.visibility_of_element_located((By.XPATH, "//iframe[starts-with(@id, 'browse-app-spotify:app:chart:')]"))) 
browser.switch_to.frame(iframe) 

# wait for header in the container to appear 
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#main-container #header"))) 

container = browser.find_element_by_id("main-container") 
+0

這是偉大的,謝謝@alexce。我可以問一下後續,現在我們已經將webdriver元素存儲在容器變量中了,我怎樣才能真正刮取容器的內容? – user3882316 2015-04-05 22:31:32

+0

@ user3882316取決於你需要什麼。如果它只是文本,則使用'container.text'。您還可以在其中找到其他元素,請參閱[定位元素](http://selenium-python.readthedocs.org/locating-elements.html)。另外,要結束這個話題,看看答案是否可以接受。謝謝。 – alecxe 2015-04-05 22:37:18