从图像中展开“a”标签,而不会丢失内容

时间:2013-08-10 15:01:20

标签: python html-parsing beautifulsoup

我想从找到的所有图片中删除“a”标记(链接)。因此,为了表现,我制作了html中所有图像的列表,并寻找包装标签并简单地删除链接。

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

这就是我做的

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.parentfindParent

时无效

我不确定我做错了什么。 自从我开始使用python以来仅仅几周时间。

3 个答案:

答案 0 :(得分:2)

unwrap()函数返回已删除的标记。树本身已经过适当修改。引自unwrap() documentation

  

replace_with()一样,unwrap()会返回已替换的标记。

换句话说:它工作正常!打印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>标签的直接子项。

答案 1 :(得分:1)

我不确定你要找的是什么输出。这是吗?

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(soup)

产量

<html><body><div> <img src="http://imgsrc.jpg"/> <img src="http://imgsrc2.jpg"/></div></body></html>

答案 2 :(得分:0)

我没有使用过Python,但看起来unwrap会返回已删除的HTML,而不是您要查找的img标记。尝试拨打soup.prettify()并查看该链接是否已删除。