【问题标题】:How to deal with the 'ascii' codec can't encode character '\xe9' error?如何处理“ascii”编解码器无法编码字符“\xe9”错误?
【发布时间】:2022-06-15 01:14:00
【问题描述】:

我正在尝试从网站下载 Excel 文件。我的代码如下:

import os
import requests
from bs4 import BeautifulSoup
# Python 3.x
from urllib.request import urlopen, urlretrieve, quote
from urllib.parse import urljoin
import urllib

headers={"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"}
resp = requests.get("https://www.elections.on.ca/en/resource-centre/elections-results.html#accordion2022ge")
soup = BeautifulSoup(resp.text,"html.parser")

for link in soup.find_all('a', href=True):
#    print(link)
    if 'xlsx' in link['href']:
        print(link['href'])
        url="https://www.elections.on.ca/"+link['href']
#        print(url)
        file= url.split("/")[-1].split(".")[0]+".xlsx"
#        print(file)
        urllib.request.urlretrieve(url, file)  

但是,当这个“https://www.elections.on.ca//content/dam/NGW/sitecontent/2022/results/Vote%20Totals%20From%20Official%20Tabulation%20 -%20Orléans%20076.xlsx" 正在尝试打开

---------------------------------------------------------------------------
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-9-e1694f5ee458> in <module>
      8         file= url.split("/")[-1].split(".")[0]+".xlsx"
      9 #        print(file)
---> 10         urllib.request.urlretrieve(url, file)
...

UnicodeEncodeError: 'ascii' codec can't encode characters in position 101-102: ordinal not in range(128). 

谢谢!

【问题讨论】:

  • 显示更多的回溯 - 您发布的代码的哪一行错误来自?
  • 您好,我已经添加了有关该错误的更多信息。我无法发布完整的错误,因为 stackoverflow 抱怨代码太多。

标签: python web-scraping beautifulsoup


猜你喜欢
  • 2015-04-13
  • 2015-10-21
  • 2017-03-31
  • 2016-04-29
  • 1970-01-01
  • 2015-02-03
  • 2019-09-01
  • 1970-01-01
相关资源
最近更新 更多