【发布时间】:2011-03-14 01:12:21
【问题描述】:
我需要使用 Python 从网页中提取元关键字。我在想这可以使用 urllib 或 urllib2 来完成,但我不确定。有人有什么想法吗?
我在 Windows XP 上使用 Python 2.6
【问题讨论】:
标签: python extract webpage keyword urllib
我需要使用 Python 从网页中提取元关键字。我在想这可以使用 urllib 或 urllib2 来完成,但我不确定。有人有什么想法吗?
我在 Windows XP 上使用 Python 2.6
【问题讨论】:
标签: python extract webpage keyword urllib
BeautifulSoup 是使用 Python 解析 HTML 的好方法。
特别是,查看 findAll 方法: http://www.crummy.com/software/BeautifulSoup/documentation.html
【讨论】:
lxml 比 BeautifulSoup 更快(我认为)并且具有更好的功能,同时相对易于使用。示例:
52> from urllib import urlopen
53> from lxml import etree
54> f = urlopen( "http://www.google.com" ).read()
55> tree = etree.HTML( f )
61> m = tree.xpath( "//meta" )
62> for i in m:
..> print etree.tostring( i )
..>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-2"/>
编辑:另一个例子。
75> f = urlopen( "http://www.w3schools.com/XPath/xpath_syntax.asp" ).read()
76> tree = etree.HTML( f )
85> tree.xpath( "//meta[@name='Keywords']" )[0].get("content")
85> "xml,tutorial,html,dhtml,css,xsl,xhtml,javascript,asp,ado,vbscript,dom,sql,colors,soap,php,authoring,programming,training,learning,b
eginner's guide,primer,lessons,school,howto,reference,examples,samples,source code,tags,demos,tips,links,FAQ,tag list,forms,frames,color table,w3c,cascading
style sheets,active server pages,dynamic html,internet,database,development,Web building,Webmaster,html guide"
顺便说一句:XPath 值得了解。
另一个编辑:
或者,您可以只使用正则表达式:
87> f = urlopen( "http://www.w3schools.com/XPath/xpath_syntax.asp" ).read()
88> import re
101> re.search( "<meta name=\"Keywords\".*?content=\"([^\"]*)\"", f ).group( 1 )
101>"xml,tutorial,html,dhtml,css,xsl,xhtml,javascript,asp,ado,vbscript,dom,sql, ...etc...
...但我发现它的可读性较差且更容易出错(但仅涉及标准模块并且仍然适合一行)。
【讨论】:
<meta> 标签的“内容”属性中,其中“名称”属性为“关键字”:)
为什么不使用正则表达式
keywordregex = re.compile('<meta\sname=
["\']keywords["\']\scontent=["\'](.*?)["\']\s/>')
keywordlist = keywordregex.findall(html)
if len(keywordlist) > 0:
keywordlist = keywordlist[0]
keywordlist = keywordlist.split(", ")
【讨论】: