如何从python中的字符串中提取某些信息?
我试图使用python从html代码中提取某些信息。 例如:如何从python中的字符串中提取某些信息?,python,html,string,Python,Html,String,我试图使用python从html代码中提取某些信息。 例如: <a href="#tips">Visit the Useful Tips Section</a> and I would like to get result : Visit the Useful Tips Section <div id="menu" style="background-color:#FFD700;height:200px;width:100px;float:left;">
<a href="#tips">Visit the Useful Tips Section</a>
and I would like to get result : Visit the Useful Tips Section
<div id="menu" style="background-color:#FFD700;height:200px;width:100px;float:left;">
<b>Menu</b><br />
HTML<br />
CSS<br />
and I would like to get Menu HTML CSS
我想得到一个结果:访问有用的提示部分
菜单
HTML
CSS
我想得到菜单HTML CSS
换句话说,我希望得到到之间的一切
我试图编写一个python函数,将html代码作为字符串,然后从中提取信息。我卡在string.split('您应该使用适当的HTML解析库,例如模块。您应该使用适当的HTML解析库,例如模块。
string=''
re.findall(']*>(.*]*>',string)//return“访问有用的提示部分”
string=''
re.findall(']*>(.*]*>',string)//return“访问有用的提示部分”
我知道您试图去掉HTML标记,只保留文本
可以定义表示标记的正则表达式。
然后用空字符串替换所有匹配项
例如:
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
def删除html标签(数据):
p=重新编译(r“”)
返回p.sub(“”,数据)
参考资料:
我知道您试图去掉HTML标记,只保留文本 可以定义表示标记的正则表达式。 然后用空字符串替换所有匹配项 例如:
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
def删除html标签(数据):
p=重新编译(r“”)
返回p.sub(“”,数据)
参考资料:
您可以使用html解析器
>>> import lxml.html as lh
>>> st = ''' load your above html content into a string '''
>>> d = lh.fromstring(st)
>>> d.text_content()
'Visit the Useful Tips Section \nand I would like to get result : Visit the Useful Tips Section\n\n\nMenu\nHTML\nCSS\nand I would
like to get Menu HTML CSS\n'
或者你可以
>>> for content in d.text_content().split("\n"):
... if content:
... print content
...
Visit the Useful Tips Section
and I would like to get result : Visit the Useful Tips Section
Menu
HTML
CSS
and I would like to get Menu HTML CSS
>>>
您可以使用html解析器
>>> import lxml.html as lh
>>> st = ''' load your above html content into a string '''
>>> d = lh.fromstring(st)
>>> d.text_content()
'Visit the Useful Tips Section \nand I would like to get result : Visit the Useful Tips Section\n\n\nMenu\nHTML\nCSS\nand I would
like to get Menu HTML CSS\n'
或者你可以
>>> for content in d.text_content().split("\n"):
... if content:
... print content
...
Visit the Useful Tips Section
and I would like to get result : Visit the Useful Tips Section
Menu
HTML
CSS
and I would like to get Menu HTML CSS
>>>
我会使用-格式错误的html会让它变得不那么古怪。我会使用-格式错误的html会让它变得不那么古怪。你试过使用任何html解析库吗?或者你可以通过删除所有标记来处理文件(不过使用
标记有点棘手)。您是否尝试过使用任何HTML解析库?或者您可以通过删除所有标记来实际处理文件(不过使用
标记有点棘手)@lazyr:取决于上下文…如果您对标记结构了解得足够多并且没有歧义,那么一个简单的regexp可以比一个完整的HTML解析器以更少的开销工作。但是您确实必须知道regexp何时可以使用,何时可以使用HTML解析器…@lazyr:取决于上下文…如果您对标记结构并且没有歧义,一个简单的regexp可以比一个完整的HTML解析器以更少的开销工作。但是你确实必须知道regexp什么时候可以,什么时候可以使用HTML解析器。。。