python - Unicode编码错误: 'ascii' codec can't encode characters in position 15-17: ord inal not in range(128)

标签 python python-3.x beautifulsoup python-unicode

我在运行以下代码时遇到了困难。

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import re
import csv

file = open("Test.CSV", "r")
reader = csv.reader(file)
for line in reader:
    text = line[5]
    lst = re.findall('(http.?://[^\s]+)', text)

    if not lst: print('Empty List')
    else:
        try:
            for url in lst:
                html = urllib.request.urlopen(url, context=ctx).read()
                soup = BeautifulSoup(html, 'html.parser')
                title = soup.title.string
                str_title = str (title)
                if 'Twitter' in str_title:
                    if len(lst) > 1: break
                    else: continue
                else:
                    print (str_title, ',', url)
        except urllib.error.HTTPError as err:
            if err.code == 404:
                print ('Invalid Twitter Link')

上面提到的代码读取一个 csv 文件,选择一列,然后使用正则表达式解析该文件以获取单行中的所有超链接,然后我使用 BeautifulSoup 解析超链接以获取页面的“标题字符串” .

现在,每当我运行此代码时,它都会停止对特定行工作,并抛出错误“UnicodeEncodeError:'ascii'编解码器无法对位置 15-17 中的字符进行编码:序数不在范围(128)中”

我如何使用这里的 Unicode 字符串? 任何帮助将不胜感激。

最佳答案

错误消息显示问题发生在urllib.request.urlopen(url, context=ctx)中。看起来至少有一个 URL 包含非 ASCII 字符。

要做什么?

您可以尝试引用该网址:

html = urllib.request.urlopen(urllib.parse.quote(url, errors='ignore'), context=ctx).read()

这将防止 UnicodeEncodeError,但会默默地构建一个错误的 URL,这可能会在以后导致问题。

我的建议是捕获 UnicodeEncodeError 并显示一条错误消息,这将有助于了解幕后发生的情况以及如何实际修复它:

for url in lst:
    try:
        html = urllib.request.urlopen(url, context=ctx).read()
        soup = BeautifulSoup(html, 'html.parser')
        title = soup.title.string
        ...
    except UnicodeEncodeError as e:
        print("Incorrect URL {}".format(url.encode('ascii', errors='backslashreplace')))

errors='backslashreplace' 选项将转储有问题的字符的代码

关于python - Unicode编码错误: 'ascii' codec can't encode characters in position 15-17: ord inal not in range(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243341/

相关文章:

python - 为什么 pow(a, d, n) 比 a**d % n 快这么多?

python - 使用每月日期计算累积流失率 - 日期问题很重要

python - 为什么最好的做法是在 requirements.txt 中包含依赖项的依赖项?

python - Beautifulsoup,给url添加属性信息(资源id)

python - scrapy 不通过 POST 请求发送 Cookie

Python:在函数中使用在类内部完成的导入

python - 除非按顺序,否则不会读取路径

python-3.x - Python 对象引用解决方法

python - 导入错误 : cannot import name 'BeautifulSoup4'

python - 格式化 BeautifulSoup 的输出