我需要从给定的网页数据中删除所有html标记。我用正则表达式尝试了这个:
import urllib2
import re
page = urllib2.urlopen("http://www.frugalrules.com")
from bs4 import BeautifulSoup, NavigableString, Comment
soup = BeautifulSoup(page)
link = soup.find('link', type='application/rss+xml')
print link['href']
rss = urllib2.urlopen(link['href']).read()
souprss = BeautifulSoup(rss)
description_tag = souprss.find_all('description')
content_tag = souprss.find_all('content:encoded')
print re.sub('<[^>]*>', '', content_tag)
但是re.sub的语法是:
re.sub(pattern, repl, string, count=0)
所以,我将代码修改为(而不是上面的print语句):
for row in content_tag:
print re.sub(ur"<[^>]*>",'',row,re.UNICODE
但它会出现以下错误:
Traceback (most recent call last):
File "C:\beautifulsoup4-4.3.2\collocation.py", line 20, in <module>
print re.sub(ur"<[^>]*>",'',row,re.UNICODE)
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
我做错了什么?
答案 0 :(得分:1)
代码的最后一行尝试:
print(re.sub('<[^>]*>', '', str(content_tag)))