使用Beautifulsoup去除特定标签

使用Beautifulsoup去除特定标签

试用了Beautifulsoup,的确是个神器。 
在抓取到网页时,会出现很多不想要的内容,例如<script>标签,利用beautifulsoup可以很容易去掉。   

 soup = BeautifulSoup('<script>a</script>Hello World!<script>b</script>') 
 [s.extract() for s in soup(‘script’)] 
 soup 
Hello World!

如果有多个标签也可以:

 [s.extract() for s in soup([‘script’, ‘iframe’])]               

 获取所有文本

# tag = soup.find('span')
# print(tag.string)          # 获取
# tag.string = 'new content' # 设置
# print(soup)
 
# tag = soup.find('body')
# print(tag.string)
# tag.string = 'xxx'
# print(soup)
 
# tag = soup.find('body')
# v = tag.stripped_strings  # 递归内部获取所有标签的文本
# print(v)

  

猜你喜欢

转载自www.cnblogs.com/zjchao/p/9067533.html