python - 从图像中解开 "a"标签,而不丢失内容

标签 python html-parsing beautifulsoup

我想从找到的所有图像中删除“a”标签(链接)。因此,为了提高性能,我在 html 中列出了所有图像,并寻找包装标签并简单地删除链接。

我正在使用 BeautifulSoup,不确定我做错了什么,它不是删除 a 标签,而是删除内部内容。

这就是我所做的

from bs4 import BeautifulSoup

html = '''<div> <a href="http://somelink"><img src="http://imgsrc.jpg" /></a> <a href="http://somelink2"><img src="http://imgsrc2.jpg /></a>"  '''
soup = BeautifulSoup(html)
for img in soup.find_all('img'):
    print 'THIS IS THE BEGINING /////////////// '
    #print img.find_parent('a').unwrap()
    print img.parent.unwrap()

这给了我以下输出

> >> print img.parent() 
<a href="http://somelink"><img src="http://imgsrc.jpg" /></a> 
<a href="http://somelink2"><img src="http://imgsrc2.jpg /></a>

> >> print img.parent.unwrap() 
<a href="http://somelink"></a> 
<a href="http://somelink2"></a>

我已经尝试过replaceWithreplaceWithChildren但当我使用 object.parent 时不起作用或findParent

我不知道我做错了什么。 距离我开始使用 Python 才几周时间。

最佳答案

unwrap()函数返回已删除的标签。树本身已被适当修改。引用自 unwrap() documentation :

Like replace_with(), unwrap() returns the tag that was replaced.

换句话说:它工作正常!打印 img父级而不是 unwrap() 的返回值看到 <a>标签确实已被删除:

>>> from bs4 import BeautifulSoup
>>> html = '''<div> <a href="http://somelink"><img src="http://imgsrc.jpg" /></a> <a href="http://somelink2"><img src="http://imgsrc2.jpg /></a>"  '''
>>> soup = BeautifulSoup(html)
>>> for img in soup.find_all('img'):
...     img.parent.unwrap()
...     print img.parent
... 
<a href="http://somelink"></a>
<div> <img src="http://imgsrc.jpg"/> <a href="http://somelink2"><img src="http://imgsrc2.jpg /&gt;&lt;/a&gt;"/></a></div>
<a href="http://somelink2"></a>
<div> <img src="http://imgsrc.jpg"/> <img src="http://imgsrc2.jpg /&gt;&lt;/a&gt;"/></div>

这里 python 回显 img.parent.unwrap()返回值,后跟 print 的输出显示 <img> 的父级的语句标签现在是 <div>标签。第一个打印显示其他 <img>标签仍然包裹着,第二个打印显示它们都是 <div> 的直接子代。标签。

关于python - 从图像中解开 "a"标签,而不丢失内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18163139/

相关文章:

java - 如何使用 jsoup 从网页中的所有段落中提取完整 URL

python - 如何在python上获取子链接

python - PyQt - 如何使用 QItemDelegate 在表格 View 中设置 QComboBox

python - 如何将 Python 列表格式化为已初始化的 C 数组?

java - 如何在java中使用Jsoup导航网站

python - BeautifulSoup tag.children 只获取奇数元素

python - Beautifulsoup4 - 通过强标签值识别信息仅适用于标签的某些值

python - 在具有自由和固定参数的 sympy 中使用最小化函数 ('SLSQP' 方法)

python - 为什么来自keras的CNN权重只是一维的?

python - 用 python 替换 HTML 中的粗体标题