【问题标题】:Handle angle bracket in pre tag using BeautifulSoup使用 BeautifulSoup 处理 pre 标签中的尖括号
【发布时间】:2019-06-15 22:56:50
【问题描述】:

我有一个这样的字符串

html = "<pre>City_<cityname>_001</pre>"

在尝试使用 BeautifulSoup 4 解析这个时,使用以下代码,

>>> from bs4 import BeautifulSoup
>>> html = "<pre>City_<cityname>_001</pre>"
>>> soup = BeautifulSoup(html, "html.parser")
>>> soup
<pre>City_<cityname>_001</cityname></pre>
>>> soup.text
City__001

可以看出,BeautifulSoup 将cityname 视为一个新标签。

有没有什么方法可以避免这种情况以获得正确的文本和 html?

【问题讨论】:

  • 那么你希望这个例子的输出是什么?
  • 想要的输出是City_&lt;cityname&gt;_001

标签: python python-3.x beautifulsoup html-parsing


【解决方案1】:

解析器会忽略注释。您可以在解析之前将&lt;pre&gt; 的内容设为评论,然后在解析之前将extract() 的内容设为评论。

import bs4
html = "<pre>City_<cityname>_001</pre>"
soup = bs4.BeautifulSoup(html.replace("<pre>","<pre><!--").replace("</pre>","--></pre>"), "lxml")
pre=soup.find('pre')
pre_comment=pre.find(text=lambda text: isinstance(text, bs4.Comment)).extract()
print(pre_comment)

输出:

City_<cityname>_001

【讨论】:

    【解决方案2】:

    这有点小技巧,但是您可以替换用括号括起来的字符串,然后使用以下结果格式化字符串:

    from bs4 import BeautifulSoup as soup
    html = "<pre>City_<cityname>_001</pre>"
    _html, _vals = re.sub('(?<=_)\<\w+\>(?=_)', '{}', html), re.findall('(?<=_)\<\w+\>(?=_)', html)
    new_result = soup(_html, 'html.parser').find('pre').text.format(*_vals)
    

    输出:

    'City_<cityname>_001'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-20
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多