【问题标题】:Unicode characters replaced with question marks when scraping web page in Python 2.7.10在 Python 2.7.10 中抓取网页时将 Unicode 字符替换为问号
【发布时间】:2015-11-16 06:21:48
【问题描述】:

我有一些简单的 python 代码可以用 urllib2 抓取网页:

response = urllib2.urlopen(url)
charset = response.headers.getheader("Content-Type")
charset = charset[charset.index("charset=") + 8:]
html = response.read()
html = " ".join(html.split())
html = html.decode(charset)
html = html.replace("amp;", "").replace("'", "'")

我的问题是我正在抓取的页面中有 Te Reo Māori 单词,因此它有很多包含宏的单词,例如。 “普太奥。”当我打印 HTML 时,所有的长音字母都替换为问号,我没有使用任何替换解码方法。它甚至在没有任何解码、拆分或连接的情况下发生。

同一站点上还有另一个页面包含一些相同的单词,并且宏在 python 中显示完全正常。我还注意到该页面的响应标头中的字符集是 utf-8,而带有问号的页面是 ISO-8859-1,因此可能与它有关。

带有问号的网站链接是http://www.nzqa.govt.nz/ncea/assessment/search.do?query=reo+maori&view=all&level=01

另一个页面是http://www.nzqa.govt.nz/qualifications-standards/qualifications/ncea/subjects/

【问题讨论】:

    标签: python python-2.7 encoding web-scraping urllib2


    【解决方案1】:

    当服务器无法识别请求来自的用户代理时,似乎服务器响应错误的内容类型。当我在我的机器上尝试时,我得到了类似的结果。

    将有效的User-Agent 添加到请求标头后,我能够正确获取响应的utf-8 编码。我不确定这是否是解决这种情况的最佳方法,但它应该可以让您的代码正常工作。示例 -

    req = urllib2.Request(url, headers = {"Connection":"keep-alive", "User-Agent":"Mozilla/5.0"})
    response = urllib2.urlopen(req)
    #After this rest of your original code.
    

    【讨论】:

      【解决方案2】:

      在您的第一个链接上使用请求和漂亮的汤。

      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      from bs4 import BeautifulSoup
      import requests
      
      url = "http://www.nzqa.govt.nz/ncea/assessment/search.do?     query=reo+maori&view=all&level=01"
      headers= {"User-Agent":"Mozilla/5.0"}
      r = requests.get(url, headers=headers)
      # print(r.content)
      print(r.encoding)
      print(r.headers['content-type'])
      data = r.text
      data1 = data.encode('UTF-8')
      soup = BeautifulSoup(data1)
      text = soup.get_text()
      text2 = text.encode('utf-8', 'ignore')
      # text2 = text.encode('ascii', 'ignore')
      print(text2)
      

      哪一行 text2 取决于你接下来要做什么。

      注意使用 Anand 建议的标题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 2016-07-04
        • 2019-08-23
        相关资源
        最近更新 更多