python - 从网页中提取元关键字?

标签 python extract webpage keyword urllib

我需要使用 Python 从网页中提取元关键字。我在想这可以使用 urllib 或 urllib2 来完成,但我不确定。有人有什么想法吗?

我在 Windows XP 上使用 Python 2.6

最佳答案

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...

...但我发现它的可读性较差且更容易出错(但仅涉及标准模块并且仍然适合一行)。

关于python - 从网页中提取元关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3215830/

相关文章:

python - 在 python 中使用 super 对撞机

python - 如何让 DjangoModelFactory 创建模型而不将其保存到数据库?

linux - 从存档中提取确切文件的快速方法

html - 使用 SVG 代替 html/css

c++ - 我怎样才能得到网页的内容

python - 让 Tkinter 等到按下按钮

python - 如何在 python pandas 中处理零日期时间?

javascript - 从任何类型的网址中提取域名

css - 如何使用 webpack 2 分离 css 文件中的 less 文件?