首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用`portia`从html中获取`keywords`

如何使用`portia`从html中获取`keywords`
EN

Stack Overflow用户
提问于 2015-09-08 09:48:30
回答 1查看 97关注 0票数 0

现在我想从一个网页中抓取keywords元和description,如下所示:

代码语言:javascript
复制
<html>
<head>
<title>test page</title>
<meta name="keywords" content="A,B,C">
<meta name="description" content="the description a page">
....

我昨天在谷歌上搜索,但是不知道,请给我一些建议。

EN

回答 1

Stack Overflow用户

发布于 2015-09-08 10:28:15

你甚至不需要scrapy来做这件事。您可以使用标准库类HTMLParser来完成此操作。

代码语言:javascript
复制
#!/usr/bin/python3
try: 
    from html.parser import HTMLParser
except ImportError:
    import HTMLParser

class MyHTMLParse(HTMLParser):
    TAG = "meta"
    NAMES = ['keywords', 'description']
    def __init__(self):
        HTMLParser.__init__(self)
        self.contents = {}
    def handle_starttag(self, tag, attrs):
        if tag == MyHTMLParse.TAG:
            attributes = {i[0] : i[1] for i in attrs}
            if attributes.get("name", None) in MyHTMLParse.NAMES:
                self.contents[attributes["name"]] = attributes["content"]


parser = MyHTMLParse()

# Feed parser the website with parser.feed(), then access the information with
# parser.contents as a dictionary with keys "keywords" and "description"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32448105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档