2015-04-04 98 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