使用Beautiful Soup解析时,删除头标记之间的任何内容

时间:2013-10-24 16:36:44

标签: python beautifulsoup

我已经搜索过,但没有找到合适的回复。

url = "http://en.wikipedia.org/wiki/Bryan_Greenberg"
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
try:
    ourUrl = opener.open(url).read()
    soup = BeautifulSoup(ourUrl)
except Exception,err:
    continue
dem = soup.findAll('p')

我刚刚复制了部分脚本。如何删除标题和头标记中的所有内容。所以它不是汤。谢谢你。

1 个答案:

答案 0 :(得分:1)

我没有安装BeautifulSoup所以它没有经过测试,但我应该这样做:

使用extract()方法:

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)
a_tag = soup.a

i_tag = soup.i.extract()

a_tag
# <a href="http://example.com/">I linked to</a>

代替soup.i.extract(),将您不需要的标记名称设为soup.head.extract()。请注意,这可能会从文档中删除所有头部或标题标签(如果碰巧有任何额外的标签),我根本就不知道从未使用过这个功能。

相关问题