【问题标题】:How can I parse a dynamic page using Python? [duplicate]如何使用 Python 解析动态页面? [复制]
【发布时间】:2016-07-13 13:23:32
【问题描述】:

我正在使用 Ghost 和 BeautifulSoup 来解析 HTML 页面。我遇到的问题是此页面的内容是动态的(使用 angularJS 创建)。一开始,html 只显示类似“请稍候!页面加载”之类的内容。几秒钟后,会出现 html 的内容。使用 Ghost 和 BeatifulSoup,我只得到了加载页面的 HTML 代码,只有 2 个小 div。 URL 保持不变。是否有可能等到“真实”内容加载完毕?

【问题讨论】:

    标签: python html angularjs beautifulsoup


    【解决方案1】:

    通过seleniumwait 自动在真实浏览器中加载页面(无头,如PhantomJS 也是一个选项)以显示所需的内容,获取.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")
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2019-11-02
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-27
        • 2021-06-21
        • 1970-01-01
        • 2013-08-04
        相关资源
        最近更新 更多