【问题标题】:Grab string between HTML tags抓取 HTML 标签之间的字符串
【发布时间】:2020-07-17 10:38:06
【问题描述】:

我有一长串 HTML 代码。我正在寻找两个特定标签之间的所有文本:<row></row>

例如:

str = "<row> hello, this is an example </row> more example text <row> even more </row>

想要的输出:

new_list = ['hello, this is an example', 'even more']

提前致谢!

【问题讨论】:

    标签: python string text split


    【解决方案1】:

    你可以用 re 来捕捉行标签之间的文本:

    import re
    
    
    str = "<row> hello, this is an example </row> more example text <row> even more </row>"
    test=re.findall('<row>(.*?)</row>',str)
    print(test)
    

    结果:

    [' hello, this is an example ', ' even more ']
    

    【讨论】:

    • 标签嵌套时会发生什么?众所周知,您无法使用正则表达式解析 HTML。请不要为复杂的解析问题提供正则表达式答案,至少要解决这些限制。
    【解决方案2】:

    使用HTML parser library

    import bs4
    
    s = "<row> hello, this is an example </row> more example text <row> even more </row>"
    soup = bs4.BeautifulSoup(s)
    result = [str(x) for x in soup.find_all('row')]
    

    与基于纯标记化的答案不同(例如,通过正则表达式),当 HTML 标记嵌套时,这将继续有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多