我在运行以下代码时遇到了困难 .
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解析超链接以获取页面的“ Headers 字符串” .
现在,每当我运行此代码时,它将停止为特定行工作,并抛出错误“UnicodeEncodeError:'ascii'编解码器无法编码位置15-17中的字符:序数不在范围内(128)”
我如何使用Unicode字符串在这里工作?任何帮助将非常感激 .
1 回答
错误消息显示问题发生在
urllib.request.urlopen(url, context=ctx)
中 . 看起来至少有一个URL包含非ASCII字符 .该怎么办?
您可以尝试引用该网址:
这将阻止
UnicodeEncodeError
,但会默默地构建一个错误的URL,这可能会导致以后出现问题 .我的建议是捕获UnicodeEncodeError并显示一条错误消息,这将有助于理解幕后发生的事情以及如何实际修复它:
errors='backslashreplace'
选项将转储违规字符的代码