【问题标题】:Get return value from HTMLParser class to main class从 HTMLParser 类获取返回值到主类
【发布时间】:2014-03-10 10:40:21
【问题描述】:

这是我当前的代码:

HTMLParser 类:

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        if tag == "a":
            for name, value in attrs:
                if name == "href":
                    print value

主类:

html = urllib2.urlopen(url).read()
MyHTMLParser().feed(html)

待办事项: 使“价值”的任何想法都可以返回主类吗? 感谢提前。

【问题讨论】:

标签: python html python-2.7 html-parsing href


【解决方案1】:

您将要收集的信息存储在解析器实例中:

class MyHTMLParser(HTMLParser):
    def __init__(self):
         HTMLParser.__init__()
         self.links = []

    def handle_starttag(self, tag, attrs):
        if tag == "a" and 'href' in attrs:
            self.links.append(attrs['href'])

然后,在您将 HTML 输入解析器后,您可以从实例中检索 links 属性

parser = MyHTMLParser()
parser.feed(html)
print parser.links

对于解析 HTML,我衷心建议您查看 BeautifulSoup

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
links = [a['href'] for a in soup.find_all('a', href=True)]

【讨论】:

  • 无法使用 BeautifulSoup,因为我使用的是 python 2.7 版本
  • @azmilhafiz:BeautifulSoup 是一个适用于 Python 2 和 Python 3,包括 Python 2.7 的插件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2014-01-07
  • 2014-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多