如何在我们要提取的文本中忽略html标记?

2024-05-17 04:05:02 发布

您现在位置:Python中文网/ 问答频道 /正文

{/strong>要在源代码之间打印。我用了下面的代码。在

import urllib2
import re
url = ['http://recipes.latimes.com/recipe-restaurant-1833s-bacon-cheddar-biscuits-maple-chile-butter/']
htmlfile = urllib2.urlopen('http://recipes.latimes.com/recipe-restaurant-1833s-bacon-cheddar-biscuits-maple-chile-butter/')
htmltext = htmlfile.read()
regex2 =  '<p><span class="step_leadin">(.+?)</p>'
pattern2 = re.compile(regex2)
method = re.findall(pattern2,htmltext)
print method

我要提取的html部分是。在

^{pr2}$

问题是,当我使用“print method”命令时,它还会给出这两个标记之间的所有文本,包括“</span>”。但是我不希望</span>在输出中被打印出来。有没有办法在提取我想要的文本时忽略标记。在


Tags: importrecomhttprecipeurllib2restaurantmethod
2条回答

我相信heinst的答案更好,但是既然您坚持使用regex,那么您可以这样做:

import re

html = '<p><span class="step_leadin">Step1</span>Carefully transfer the biscuits to a rimmed baking sheet, spacing them an inch or so apart</p>'

print re.sub(r'<[^>]*?>', '', html)

我强烈建议您不要使用regex来解析html,因为html is not regular.应该使用类似BeautifulSoup或{a3}之类的html/xml解析器。下面是您尝试使用beauthoulGroup执行的操作的示例:

from bs4 import BeautifulSoup

html = '<p><span class="step_leadin">Step1</span>Carefully transfer the biscuits to a rimmed baking sheet, spacing them an inch or so apart</p>'

bs = BeautifulSoup(html)

for p in bs.find_all('p'):
    print p.text

相关问题 更多 >