【问题标题】:Extract Meta Keywords From Webpage?从网页中提取元关键字?
【发布时间】:2011-03-14 01:12:21
【问题描述】:

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

我在 Windows XP 上使用 Python 2.6

【问题讨论】:

标签: python extract webpage keyword urllib


【解决方案1】:

BeautifulSoup 是使用 Python 解析 HTML 的好方法。

特别是,查看 findAll 方法: http://www.crummy.com/software/BeautifulSoup/documentation.html

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 好的,但是文档的关键字在哪里。我需要根据我拥有的列表检查元数据中的关键字。
    • 如您所见,它们位于&lt;meta&gt; 标签的“内容”属性中,其中“名称”属性为“关键字”:)
    • 还要确保尽可能使用缓存内容developer.yahoo.com/python/python-caching.html
    【解决方案3】:

    为什么不使用正则表达式

    keywordregex = re.compile('<meta\sname=
    ["\']keywords["\']\scontent=["\'](.*?)["\']\s/>')
    
    keywordlist = keywordregex.findall(html)
    if len(keywordlist) > 0:
        keywordlist = keywordlist[0]
        keywordlist = keywordlist.split(", ")
    

    【讨论】:

      猜你喜欢
      • 2015-09-06
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多