zoukankan      html  css  js  c++  java
  • Beautiful Soup 解决爬虫编码格式问题,Beautiful Soup编码格式

    一。 为什么要用解析框架 bs4

      我觉得爬虫最难得问题就是编码格式,因为你不知道要爬取目标网站的编码格式,有可能是Unicode,utf-8, ASCII , gbk格式,但是使用Beautiful Soup解析后,文档都被转换成了Unicode,通过Beautiful Soup输出文档时,不管输入文档是什么编码方式,输出编码均为UTF-8编码, 因为 Beautiful Soup用了 编码自动检测 子库来识别当前文档编码并转换成Unicode编码。

      编码自动检测 功能大部分时候都能猜对编码格式,但有时候也会出错.有时候即使猜测正确,也是在逐个字节的遍历整个文档后才猜对的,这样很慢.如果预先知道文档编码,可以设置编码参数来减少自动检查编码出错的概率并且提高文档解析速度.在创建 BeautifulSoup 对象的时候设置 from_encoding 参数

      下面一段文档用了ISO-8859-8编码方式,这段文档太短,结果Beautiful Soup以为文档是用ISO-8859-7编码:

      markup = b"<h1>xedxe5xecxf9</h1>"
      soup = BeautifulSoup(markup)
      soup.h1
      <h1>νεμω</h1>
      soup.original_encoding
      'ISO-8859-7'

      通过传入 from_encoding 参数来指定编码方式:

      soup = BeautifulSoup(markup, from_encoding="iso-8859-8")
      soup.h1
      <h1>םולש</h1>
      soup.original_encoding
      'iso8859-8'

      下面例子输入文档是Latin-1编码:

      

    markup = b'''
    <html>
      <head>
        <meta content="text/html; charset=ISO-Latin-1" http-equiv="Content-type" />
      </head>
      <body>
        <p>Sacrxe9 bleu!</p>
      </body>
    </html>
    '''
    
    soup = BeautifulSoup(markup)
    print(soup.prettify())
    # <html>
    #  <head>
    #   <meta content="text/html; charset=utf-8" http-equiv="Content-type" />
    #  </head>
    #  <body>
    #   <p>
    #    Sacré bleu!
    #   </p>
    #  </body>
    # </html>

      如果不想用UTF-8编码输出,可以将编码方式传入 prettify() 方法:

    print(soup.prettify("latin-1"))
    # <html>
    #  <head>
    #   <meta content="text/html; charset=latin-1" http-equiv="Content-type" />
    # ...

    还可以调用 BeautifulSoup 对象或任意节点的 encode() 方法,就像Python的字符串调用 encode() 方法一样:

    soup.p.encode("latin-1")
    # '<p>Sacrxe9 bleu!</p>'
    
    soup.p.encode("utf-8")
    # '<p>Sacrxc3xa9 bleu!</p>'
  • 相关阅读:
    三种方法
    渐渐明白
    出手的时候到了
    URL OpenDocument
    熟练使用IDT
    时间快到了
    还是这样
    接口的多态性
    接口(interface)的使用
    抽象类(abstract class)与抽象方法
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/8194747.html
Copyright © 2011-2022 走看看