【问题标题】:Parse specific links in html using HTMLParser in python?在 python 中使用 HTMLParser 解析 html 中的特定链接?
【发布时间】:2014-12-09 08:57:28
【问题描述】:

我正在尝试从 html 文件中解析一组特定的链接,但由于我使用的是 HTMLParser,我无法访问层次结构树中的 html 信息,因此无法提取信息。

我的 HTML 如下:

<p class="mediatitle">
        <a class="bullet medialink" href="link/to/a/file">Some Content
        </a>
</p>

所以我需要提取所有其键为“href”且前一个属性为 class="bullet medialink" 的值。换句话说,我只想要存在于“bullet medialink”类的标签中的thode hrefs

到目前为止我尝试的是

from HTMLParser import HTMLParser
import urllib
# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
    if(tag == 'a'):
        for (key,value) in attrs:
            if(value == 'bullet medialink'):
                print "attr:", key

p = MyHTMLParser()
f = urllib.urlopen("sample.html")
html = f.read()
p.feed(html)
p.close()

【问题讨论】:

    标签: python html parsing


    【解决方案1】:

    为此我想要 Bs4。 Bs4 是第三方 html 解析器。文档:http://www.crummy.com/software/BeautifulSoup/bs4/doc/

    import urllib
    from bs4 import BeautifulSoup
    
    f = urllib.urlopen("sample.html")
    html = f.read()
    soup = BeautifulSoup(html)
    for atag in soup.select('.bullet.medialink'):  # Just enter a css-selector here
        print atag['href']  # You can also get an atrriibute with atag.get('href')
    

    或更短:

    import urllib
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(urllib.urlopen("sample.html").read())
    for atag in soup.select('.bullet.medialink'):
        print atag
    

    【讨论】:

    • 非常感谢。但是由于我正在制作一个供很多人使用的脚本,所以我想通过仅使用内置的 python 解析功能来保持简单
    • 嗯 也许你可以看看内置的 etree 库 docs.python.org/2/library/xml.etree.elementtree.html 它不是最好的,但总是比 htmlparser 好。如果你改变主意,你总是可以使用 lxml.de 它使用 etree 库,但更好用。
    【解决方案2】:

    因此,由于 HTMLParser 不是分层解析器包,因此我最终使用了一个简单的布尔标志。

    这是代码

    from HTMLParser import HTMLParser
    import urllib
    # create a subclass and override the handler methods
    class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        if(tag == 'a'):
            flag = 0
            for (key,value) in attrs:
                    if(value == 'bullet medialink' and key == 'class'):
                        flag =1
                    if(key == 'href' and flag == 1):    
                        print "link : ",value
                        flag = 0        
    
    p = MyHTMLParser()
    f = urllib.urlopen("sample.html")
    html = f.read()
    p.feed(html)
    p.close()
    

    希望有人提出更优雅的解决方案。

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 2011-09-23
      • 2019-06-07
      • 2016-01-28
      • 2010-09-12
      • 2021-10-31
      相关资源
      最近更新 更多