【问题标题】:How to render contents of a tag in unicode in BeautifulSoup?如何在 BeautifulSoup 中以 unicode 呈现标签的内容?
【发布时间】:2010-10-25 00:01:06
【问题描述】:

这是来自 WordPress 帖子详细信息页面的汤:

content = soup.body.find('div', id=re.compile('post'))
title = content.h2.extract()
item['title'] = unicode(title.string)
item['content'] = u''.join(map(unicode, content.contents))

我想在分配item['content'] 时省略封闭的div 标签。有没有办法以 unicode 呈现标签的所有子标签?比如:

item['content'] = content.contents.__unicode__()

这会给我一个 unicode 字符串而不是一个列表。

【问题讨论】:

    标签: python xml web-applications screen-scraping beautifulsoup


    【解决方案1】:

    你试过了吗:

    unicode(content)
    

    它将content 的标记转换为单个Unicode 字符串。

    编辑:如果您不想要封闭标签,请尝试:

    content.renderContents()
    

    【讨论】:

    • 是的,但我想省略封闭标签。在这种情况下是外部 DIV。
    • 好吧,renderContents() 返回一个 str 而不是 unicode。我想避免不必要的编码和解码。
    • 我检查了文档和源代码,但找不到将内容作为单个 Unicode 对象返回的方法。 renderContents() 返回一个以 UTF-8 编码的字符串。所以将 renderContents() 的结果转换为 Unicode 对象是我能找到的最好方法。
    • 是的,unicode/renderContents 组合肯定胜过我的 map/unicode 组合。
    • 我认为这个答案被接受是公平的。我记得当时我无法更改它。
    猜你喜欢
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多