2013-09-29 112 views
4

我有一個腳本來替換「ahref」標記中的單詞。不過,我想完全刪除一個href,這樣你就可以擁有沒有鏈接的Google這個詞。如何刪除文本中的所有href標記

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>') 
for a in soup.findAll('a'): 
    a['href'] = a['href'].replace("google", "mysite") 
result = str(soup) 

您也可以找到所有放置在HREF的話並放置一個「」之前和之後他們。我不知道如何。我想這是在替換之前完成的。

+0

你可以留下無意義的''嗎?你可以'刪除'['href']'。 – Ryan

回答

6

使用del a['href']代替,就像你在一個普通的詞典:

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>') 
for a in soup.findAll('a'): 
    del a['href'] 

爲您提供:

>>> print str(soup) 
<p>Hello <a>Google</a></p> 

UPDATE:

如果你想擺脫的<a>標籤共有,您可以使用.replaceWithChildren()方法:

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>') 
for a in soup.findAll('a'): 
    del a['href'] 

爲您提供:

>>> print str(soup) 
<p>Hello Google</p> 

...而且,你在評論請求(包裝用空格標籤的文本內容),可實現

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>') 
for a in soup.findAll('a'): 
    del a['href'] 
    a.setString(' %s ' % a.text) 

爲您提供:

>>> print str(soup) 
<p>Hello <a> Google </a></p> 
+0

謝謝,但谷歌我會看到一個鏈接或正常的文字。另外我怎樣才能在谷歌或href任何單詞之前放置一個空間。謝謝 – user2784753

4

您可以用漂白劑

pip install bleach 

然後用它像這樣...

import bleach 
from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup('<a href = "somesite.com">hello world</a>') 
clean = bleach.clean(soup,tags[],strip=True) 

這導致...

>>> print clean 
u'hello world' 

here是漂白的文檔。

相關問題