【问题标题】:Python3 Beautiful Soup get HTML tag anchorPython3 Beautiful Soup 获取 HTML 标签锚点
【发布时间】:2017-01-17 11:38:07
【问题描述】:

我正在尝试使用 BS4 和 Python 来保存和替换 HTML 文件中第一个 <translate> 标记的内容。

现在我正在尝试做这样的事情:

translate_bs4 = bs4_object.find('translate')
translate_key = '{{ key }}'
translate_initial = str(title_bs4)
translate_bs4.string = translate_key

我的测试用例是:

<translate>tag with <other_tag>some text</other_tag></translate>
<much_longer_file>...</much_longer_file>

而 HTML 是预期之一:

<translate>{{ key }}</translate>
<much_longer_file>...</much_longer_file>

但是translate_initial的值是

<translate>tag with <other_tag>some text</other_tag></translate>

而不是预期

tag with <other_tag>some text</other_tag>

我知道使用正则表达式可以很容易地提取它,但我想要一个更多与 DOM 相关的解决方案。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    试试这个:

    translate_bs4 = bs4_object.find('translate')
    translate_initial = translate_bs4.decode_contents(formatter="html")
    

    【讨论】:

    • 您的解决方案有效,但我遇到了一些没有等效 HTML 实体的非 ASCII 字符的问题。通过将格式化程序设置为无解决了这个问题。谢谢! :D
    猜你喜欢
    • 2019-05-30
    • 2016-07-06
    • 1970-01-01
    • 2018-01-17
    • 2019-08-03
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多