【问题标题】:How to parse and extract some html values from an html page which might not be valid?如何从可能无效的 html 页面中解析和提取一些 html 值?
【发布时间】:2016-11-09 14:20:53
【问题描述】:

我需要解析一个可能无效的 html 页面。实际上,其中很多是因为我从互联网上获得的。特别是,我需要获取一些标签的值。我可以通过正则表达式做到这一点,但我想它们不适合这项任务,尤其是因为 html 页面很大。

我的问题是,我应该选择什么库来解析这样的页面并获取我需要的标签/属性的值?

【问题讨论】:

    标签: python html parsing web-scraping


    【解决方案1】:

    试试 bs4 您可以通过

    解析html文档
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(open("*.html","r").read(),"html.parser")
    soup.title  #return the node of title
    print str(soup.title.string)  #return the text in title
    alist = soup.findAll('a')  #return a list of all nodes of tag <a>
    alist[0]['href']  #return the href attribute of this node as a str
    blist = soup.findAll('div',{'class':'container'})  #return a list of all nodes of tag <div> whose class is container
    

    更多信息请访问https://www.crummy.com/software/BeautifulSoup/bs4/doc/

    【讨论】:

    • 如果 html 页面无效怎么办?
    • 您的“无效”是什么意思?能给我举几个例子吗?
    • 如果你想运行一个爬虫,即使html页面有一些错误,它也会得到你想要的大部分信息。事实上你可以使用
    • 最大,ti pohodu tupoi。
    • @Kumakaja 然后使用除'html.parser' 之外的其他解析器。 lxml.htmlhtml5lib。两者都可以解析无效的 HTML。前者更快,后者是用纯 Python 编写的,并且像现在大多数浏览器一样解释(损坏的)HTML。有关这些解析器以及如何安装它们的信息,请参阅 BeautifulSoup 的文档。
    【解决方案2】:

    如果您真的对无效的 html 感到困扰,您可以将pre-processing 应用于提取的 html 以使其接近有效的 xml。看看如何:

    import requests
    import re
    res = requests.get('http://page.com');
    
    # remove everything before the `body` tag
    res.text = re.sub(r"(.*?)<body>",'<body>', res.text ) 
    
    # remove unneeded, long white spaces
    res.text = re.sub(r"\s+",' ', res.text ) 
    
    # make unclosed `p` tags closed 
    res.text = re.sub(r"<p>",'</p><p>', res.text )
    
    # etc.
    
    # here you start to parse your brushed-up code
    

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 2012-07-23
      • 2021-03-25
      • 2020-12-18
      • 2012-11-06
      • 1970-01-01
      • 2012-06-27
      • 2016-05-16
      • 2011-07-06
      相关资源
      最近更新 更多