关于Python爬虫提问。

  • f
    fengjianzhi
    from bs4 import BeautifulSoupimport requests
    if __name__ == "__main__":
    target = 'http://www.yqbb.gov.cn/gzdt/'
    r = requests.get(url = target)
    r.encoding = 'utf-8'
    html = r.text
    bf = BeautifulSoup(html)
    texts = bf.find_all()
    print(texts)

    目标网页<head>里有下面这行代码
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    “charset=utf-8”已经指名编码方式
    为什么r.encoding还需要指名'utf-8'(不指名会以iso-8859-1编码)?
  • z
    znm
    一个是网页的标示,一个是encode格式,这两个没啥关系吧 iOS fly ~
  • 猫了个咪的
    编程时候的encode主要用于爬取的文本内容编码格式识别转换。网页内的encode指示是给浏览器看的
  • P
    Pyrrhus
    你不指明 'utf-8' ,目标里的<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    你怎么能读出呢?
  • 嘻哈小寒
    requests文档里有说原因。

    https://2.python-requests.org/en/master/user/advanced/#encodings

    When you receive a response, Requests makes a guess at the encoding to use for decoding the response when you access the Response.text attribute. Requests will first check for an encoding in the HTTP header, and if none is present, will use chardet to attempt to guess the encoding.

    The only time Requests will not do this is if no explicit charset is present in the HTTP headers and the Content-Type header contains text. In this situation, RFC 2616 specifies that the default charset must be ISO-8859-1. Requests follows the specification in this case. If you require a different encoding, you can manually set the Response.encoding property, or use the raw Response.content.

    谷歌机翻

    当您收到响应时,Requests会在您访问Response.text属性时猜测用于解码响应的编码。请求将首先检查HTTP标头中的编码,如果不存在,将使用chardet尝试猜测编码。

    请求不会执行此操作的唯一时间是HTTP标头中不存在显式字符集且Content-Type标头包含文本。在这种情况下,RFC 2616指定默认字符集必须是ISO-8859-1。在这种情况下,请求遵循规范。如果需要不同的编码,可以手动设置Response.encoding属性,或使用原始的Response.content。
  • f
    fengjianzhi
    谢谢楼上几位hper,多谢。
  • f
    fengjianzhi
    编码方式
    当你收到一个响应时,Requests 会猜测响应的编码方式,用于在你调用 Response.text 方法时对响应进行解码。Requests 首先在 HTTP 头部检测是否存在指定的编码方式,如果不存在,则会使用 charade 来尝试猜测编码方式。

    只有当 HTTP 头部不存在明确指定的字符集,并且 Content-Type 头部字段包含 text 值之时, Requests 才不去猜测编码方式。在这种情况下, RFC 2616 指定默认字符集必须是 ISO-8859-1 。Requests 遵从这一规范。如果你需要一种不同的编码方式,你可以手动设置 Response.encoding 属性,或使用原始的 Response.content。

    以上内容来自官方文档。

    文档中说会检测head中的charset,那本例中默认不就是utf-8?为什么还需要指定。留下疑问,慢慢理解吧。
  • m
    mijuu
    http headers是指http协议里的东西,不是html文档的head tag
  • f
    fengjianzhi
    回复8#mijuu


    感谢,我搞混了,十分感谢。