use*_*753 5 html python parsing beautifulsoup
我有一个脚本来替换"ahref"标签中的单词.但是,我想完全删除一个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)
Run Code Online (Sandbox Code Playgroud)
你也可以找到放在href中的所有单词,并在它们之前和之后放置一个"".我不知道该怎么做.我想这是在更换之前完成的.
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']
Run Code Online (Sandbox Code Playgroud)
给你:
>>> print str(soup)
<p>Hello <a>Google</a></p>
Run Code Online (Sandbox Code Playgroud)
更新:
如果您想<a>完全删除标签,可以使用以下.replaceWithChildren()方法:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('<p>Hello <a href="http://google.com">Google</a></p>')
for a in soup.findAll('a'):
a.replaceWithChildren()
Run Code Online (Sandbox Code Playgroud)
给你:
>>> print str(soup)
<p>Hello Google</p>
Run Code Online (Sandbox Code Playgroud)
...并且,您在评论中请求的内容(用空格包装标签的文本内容)可以通过以下方式实现:
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)
Run Code Online (Sandbox Code Playgroud)
给你:
>>> print str(soup)
<p>Hello <a> Google </a></p>
Run Code Online (Sandbox Code Playgroud)
你可以使用漂白剂
pip install bleach
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它......
import bleach
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('<a href = "somesite.com">hello world</a>')
clean = bleach.clean(soup,tags[],strip=True)
Run Code Online (Sandbox Code Playgroud)
这导致......
>>> print clean
u'hello world'
Run Code Online (Sandbox Code Playgroud)
这是漂白的文档.