【问题标题】:UnicodeEncodeError in Python 3 and BeautifulSoup4Python 3 和 BeautifulSoup4 中的 UnicodeEncodeError
【发布时间】:2017-10-15 00:22:23
【问题描述】:

运行我的代码时,我收到此错误

UnicodeEncodeError: 'ascii' codec can't encode character '\u0303' in position 71: ordinal not in range(128)

这是我的全部代码,

from urllib.request import urlopen as uReq
from urllib.request import urlretrieve as uRet
from bs4 import BeautifulSoup as soup
import urllib

for x in range(143, 608):
    myUrl = "example.com/" + str(x)
    try:
        uClient = uReq(myUrl)
        page_html = uClient.read()
        uClient.close()
        page_soup = soup(page_html, "html.parser")

        container = page_soup.findAll("div", {"id": "videoPostContent"})

        img_container = container[0].findAll("img")
        images = img_container[0].findAll("img")

        imgCounter = 0

        if len(images) == "":
            for image in images:
                print('Downloading image from ' + image['src'] + '...')
                imgCounter += 1
                uRet(image['src'], 'pictures/' + str(x) + '.jpg')
        else:
            for image in img_container:
                print('Downloading image from ' + image['src'] + '...')
                imgCounter += 1
                uRet(image['src'], 'pictures/' + str(x) + '_' + str(imgCounter) + '.jpg')
    except urllib.error.HTTPError:
        continue

尝试过的解决方案:

我尝试将.encode/decode('utf-8').text.encode/decode('utf-8') 添加到page_soup,但它给出了这个错误。

AttributeError: 'str' / 'bytes' 对象没有属性 'findAll' 或

【问题讨论】:

  • 在哪一行抛出错误?
  • 将 page_soup 转换为字符串意味着它不再是 BeatifulSoup 对象。所以你不能使用findAll。哪一行报错了?
  • 在 uRet() [即 urlretrieve]
  • 所以其中的一个字符串没有以 uRet 理解的方式编码。我相信您想encode 任何字符串,然后再将其放入uRet。可能是images['src'].encode('utf-8')
  • 尝试将.encode('utf-8) 放入images['src'] 但它给了我:TypeError: cannot use a string pattern on a bytes-like object

标签: python encoding utf-8 beautifulsoup


【解决方案1】:

至少有一个图片 src url 包含非 ascii 字符,urlretrieve 无法处理。

>>> url = 'http://example.com/' + '\u0303'
>>> urlretrieve(url)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
UnicodeEncodeError: 'ascii' codec can't encode character '\u0303' in position 5: ordinal not in range(128)

您可以尝试其中一种方法来解决此问题。

  1. 假设这些 url 是有效的,并使用具有更好 unicode 处理能力的库来检索它们,例如 requests

  2. 假设 url 有效,但包含在传递给 urlretrieve 之前必须转义的 unicode 字符。这需要将 url 拆分为方案、域、路径等,引用路径和任何查询参数,然后再拆分;用于此的所有工具都在 urllib.parse 包中(但这可能是 requests 所做的,所以只需使用 requests)。

  3. 假设这些 url 已损坏并通过使用 try/except UnicodeEncodeError 包装您的 urlretrieve 调用来跳过它们

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2018-12-18
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多