如何使用Python解析动态页面?

时间:2016-03-25 18:35:17

标签: python html angularjs beautifulsoup

我使用Ghost和BeautifulSoup来解析HTML页面。我遇到的问题是这个页面的内容是动态的(用angularJS创建)。一开始html只显示"请等待!页面加载"。几秒钟后,html的内容出现。使用Ghost和BeatifulSoup我只获得加载页面的HTML代码,只有2个小div。 URL保持不变。是否有可能等到真实的"内容已加载?

2 个答案:

答案 0 :(得分:2)

使用phantomjs打开该页面。 使用phantomjs文件系统模块Api将其另存为本地文件。 稍后使用此本地文件句柄创建BeautifulSoup对象,然后解析页面。 见http://www.kochi-coders.com/2014/05/06/scraping-a-javascript-enabled-web-page-using-beautiful-soup-and-phantomjs/

答案 1 :(得分:2)

将页面加载到真实的浏览器中(无标题PhantomJS也是一个选项),由selenium wait自动显示所需内容,获取.page_source并将其传递给BeautifulSoup

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.PhantomJS()
driver.get("your url here")

# waiting for the page to load - TODO: change
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.ID, "content")))

data = driver.page_source
driver.close()

soup = BeautifulSoup(data, "html.parser")
相关问题