【问题标题】:Error in printing scraped webpage through bs4通过 bs4 打印抓取的网页时出错
【发布时间】:2015-01-07 10:24:23
【问题描述】:

代码:

import requests
import urllib
from bs4 import BeautifulSoup

page1 = urllib.request.urlopen("http://en.wikipedia.org/wiki/List_of_human_stampedes")
soup = BeautifulSoup(page1)
print(soup.get_text())
print(soup.prettify())

错误:

 Traceback (most recent call last):
  File "C:\Users\sony\Desktop\Trash\Crawler Try\try2.py", line 9, in <module>
    print(soup.get_text())
  File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u014d' in position 10487: character maps to <undefined>

我认为问题主要在于 urllib 包。这里我使用的是 urllib3 包。他们将 urlopen 语法从 2 版本更改为 3 版本,这可能是错误的原因。但话虽如此,我只包含了最新的语法。 Python 3.4 版

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup web-crawler


    【解决方案1】:

    由于您正在导入 requests,因此您可以使用它来代替 urllib,如下所示:

    import requests
    from bs4 import BeautifulSoup
    
    page1 = requests.get("http://en.wikipedia.org/wiki/List_of_human_stampedes")
    soup = BeautifulSoup(page1.text)
    print(soup.get_text())
    print(soup.prettify())
    

    您的问题是 python 无法对您正在抓取的页面中的字符进行编码。有关更多信息,请参见此处:https://stackoverflow.com/a/16347188/2638310

    由于维基百科页面是 UTF-8 格式,BeautifulSoup 似乎猜错了编码。尝试在代码中传递 from_encoding 参数,如下所示:

    soup = BeautifulSoup(page1.text, from_encoding="UTF-8")
    

    有关 BeautifulSoup 中编码的更多信息,请查看此处:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#encodings

    【讨论】:

    • 在编码中给出此错误文件“C:\Python34\lib\encodings\cp1252.py”,第 19 行,返回 codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' 编解码器无法对位置 10487 中的字符 '\u014d' 进行编码:字符映射到
    【解决方案2】:

    我使用的是 Python2.7,所以我在 urllib 模块中没有 request 方法。

    #!/usr/bin/python3
    # coding: utf-8
    
    import requests
    from bs4 import BeautifulSoup
    
    URL = "http://en.wikipedia.org/wiki/List_of_human_stampedes"
    soup = BeautifulSoup(requests.get(URL).text)
    print(soup.get_text())
    print(soup.prettify())
    

    https://www.python.org/dev/peps/pep-0263/

    【讨论】:

      【解决方案3】:

      将这些打印行放在 Try-Catch 块中,这样如果存在非法字符,就不会出现错误。

      try:
         print(soup.get_text())
         print(soup.prettify())
      except Exception:
         print(str(soup.get_text().encode("utf-8")))
         print(str(soup.prettify().encode("utf-8")))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多