【问题标题】:Python regex to strip html a tags without href attributePython 正则表达式去除没有 href 属性的 html a 标签
【发布时间】:2013-06-18 04:48:56
【问题描述】:

我有一个用 lxml 的 Cleaner 清理过的字符串,所以所有的链接现在都是 Content.xml 的形式。现在我想去掉所有没有 href 属性的链接,例如

<a rel="nofollow">Link to be removed</a>

应该变成

Link to be removed

同样的:

<a>Other link to be removed</a>

应该变成:

Other link to be removed

仅包含缺少 href 属性的所有链接。它不一定是正则表达式,但由于 lxml 返回一个干净的标记结构,它应该是可能的。我需要的是一个去掉了这种非功能性 a 标签的源字符串。

【问题讨论】:

  • 不要使用正则表达式来读取/操作 HTML。改用 HTML/XML 库
  • 哪个是这样做的,如何做到的?在 lxml、FilterHTML 或漂白剂中找不到此功能。另外,字符串已经被 lxml 解析过了。

标签: python html regex strip htmlcleaner


【解决方案1】:

使用drop_tag 方法。

import lxml.html

root = lxml.html.fromstring('<div>Test <a rel="nofollow">Link to be <b>removed</b></a>. <a href="#">link</a>')
for a in root.xpath('a[not(@href)]'):
    a.drop_tag()

assert lxml.html.tostring(root) == '<div>Test Link to be <b>removed</b>. <a href="#">link</a></div>'

http://lxml.de/lxmlhtml.html

.drop_tag(): 删除标记,但保留其子项和文本。

【讨论】:

  • 谢谢!!这很好用。如果我使用这个 xpath:'//a[not(@href)]',它对我有用。没有“//”,它不会找到所有嵌套链接。
【解决方案2】:

您可以使用BeautifulSoup,这样可以更轻松地找到没有href&lt;a&gt; 标签:

>>> from bs4 import BeautifulSoup as BS
>>> html = """
... <a rel="nofollow">Link to be removed</a>
... <a href="alink">This should not be included</a>
... <a>Other link to be removed</a>
... """
>>> soup = BS(html)
>>> for i in soup.find_all('a', href=False):
...     i.replace_with(i.text)
... 
>>> print soup
<html><body>Link to be removed
<a href="alink">This should not be included</a>
Other link to be removed</body></html>

【讨论】:

  • 输出文本,但我想仅在源字符串内剥离 html 标签。我将编辑我的问题以澄清这一点。
  • @Nasmon 哦,像Hello. &lt;a&gt;Test&lt;/a&gt;. Yay. 这样的东西应该是Hello. Test. Yay.
  • 没错,那太好了!
  • 谢谢海德罗!由于我已经在使用 lxml 并且没有安装 BeautifulSoup,因此我接受了 falsetru 的回答。但是有一个 BeautifulSoup 的替代品真是太好了!
  • @Nasmon,如果a标签包含另一个标签,那将会丢失。
猜你喜欢
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多