【问题标题】:How to get HTML from a beautiful soup object如何从漂亮的汤对象中获取 HTML
【发布时间】:2014-11-01 23:41:52
【问题描述】:

我有以下 bs4 对象列表:

>>> listing
<div class="listingHeader">
<h2>
....


>>> type(listing)
<class 'bs4.element.Tag'>

我想将原始 html 提取为字符串。我试过了:

>>> a = listing.contents
>>> type(a)
<type 'list'>

所以这不起作用。我该怎么做?

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    只需获取string representation

    html_content = str(listing)
    

    这是一个非美化版本。

    如果你想要一个美化的,使用prettify()方法:

    html_content = listing.prettify()
    

    【讨论】:

    • 有没有办法把它变成一个 unicode 字符串我收到一个错误:“WebDriverException: Message: u'missing ; before statement'”
    • 我一直在与元音变音 ä,ö,ü 等特殊字符作斗争。有人可能想使用soup.prettify( formatter="html" ) - 比较crummy.com/software/BeautifulSoup/bs4/doc/#output-formatters
    • 当我将 cast tag object 输入到 str 时,我得到了 \n\t\r。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 2015-11-07
    相关资源
    最近更新 更多