【问题标题】:Select tag having a dot with beautifulsoup选择带有 beautifulsoup 点的标签
【发布时间】:2019-10-18 17:41:29
【问题描述】:

如何使用beautifulsoup 选择和修改标签<Tagwith.dot> 以及其他一些文本?如果使用 beautifulsoup 无法实现,那么下一个用于 xml 文档编辑和创建的最佳库是 lxml?

from bs4 import BeautifulSoup as bs

stra = """
<body>
<Tagwith.dot>Text inside tag with dot</Tagwith.dot>
</body>"""
soup = bs(stra)

所需的 XML:

<body>
<Tagwith.dot>Edited text</Tagwith.dot>
</body>

【问题讨论】:

    标签: python xml python-3.x beautifulsoup lxml


    【解决方案1】:

    你可以使用xml.etree.elementtree来实现你想要的如下

    import xml.etree.ElementTree as ET
    
    stra = """
    <body>
    <Tagwith.dot>Text inside tag with dot</Tagwith.dot>
    </body>"""
    
    #Read xml string and convert to xml object
    xml_obj = ET.fromstring(stra)
    
    #Iterate through elements
    for elem in xml_obj:
        #If tag is found, modify the text
        if elem.tag == 'Tagwith.dot':
            elem.text = 'Edited text'
    
    #Print updated xml object as a string
    print(ET.tostring(xml_obj).decode())
    

    输出将是

    <body>
    <Tagwith.dot>Edited text</Tagwith.dot>
    </body>
    

    【讨论】:

    • 有没有办法直接选择它,而不是手动迭代和找到它,如果标签嵌套在里面,我宁愿让库进行递归迭代。
    • 当然,让我看看我们如何实现它@Zid
    【解决方案2】:

    BS4 假定所有标记并将其转换为小写。下面的代码工作正常。提供小写的标签名称。

    from bs4 import BeautifulSoup as bs
    
    stra = """
    <body>
    <Tagwith.dot>Text inside tag with dot</Tagwith.dot>
    </body>"""
    soup = bs(stra, 'html.parser')
    
    print(soup.find_all('tagwith.dot'))
    
    

    输出:

    [<tagwith.dot>Text inside tag with dot</tagwith.dot>]
    

    【讨论】:

    • 我明白了。我认为它不起作用,因为 "." 可能与 css 类语法有关。完美的。它现在正在使用tag_string.lower()
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2015-03-11
    • 2016-01-10
    相关资源
    最近更新 更多