【问题标题】:Exception has occurred: UnicodeDecodeError 'utf-8' codec can't decode byte 0xf1 in position发生异常:UnicodeDecodeError 'utf-8' codec can't decode byte 0xf1 in position
【发布时间】:2020-09-21 19:27:21
【问题描述】:

我正在这个网站上进行抓取,但是当我迭代时,我发现以下消息: 发生异常:UnicodeDecodeError “utf-8”编解码器无法解码位置 614 中的字节 0xf1:无效的继续字节

我的代码:

import requests
from bs4 import BeautifulSoup as soup 

links=['https://www.yapo.cl/vi/74410346.htm?ca=15_s', 'https://www.yapo.cl/vi/73845701.htm?ca=15_s']

for link in links:
    uClient = requests.get(link)
    soup = soup(uClient.content, "html.parser")
    containers = soup.findAll("div",{"class":"price price-final"})
    print(containers)

【问题讨论】:

  • 您正在抓取网页而不检查响应的状态。我运行它并获得 403 状态 - 禁止。考虑在将 html 加载到汤之前使用 uClient.raise_for_status()。如果状态码为 400 或 500,这将引发错误。
  • 我已经这样做了,但这不是问题,(我输入了代码 200)。 :-( 无论如何感谢您的帮助
  • 对不起,我看到了 403 错误,没有再继续。 “findAll”应该是“find_all”。我会推荐 print(soup.prettify()) - 找到无法解码的字符。也许你需要 uClient.text
  • 现在我知道问题是“ñ”,无法解码
  • 您能否通过打印 uClient.encoding 和 uClient.apparent_encoding 来检查您正在使用的编码?

标签: python-3.x beautifulsoup python-requests screen-scraping


【解决方案1】:

我试图获取一个 URL 的数据,它对我有用。

import requests
from bs4 import BeautifulSoup

headers = {
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)",
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "accept-charset": "cp1254,ISO-8859-9,utf-8;q=0.7,*;q=0.3",
    "accept-encoding": "gzip,deflate,sdch",
    "accept-language": "tr,tr-TR,en-US,en;q=0.8",
}

with requests.Session() as session:
    session.headers = headers
    r = session.get('https://www.yapo.cl/vi/74410346.htm?ca=15_s', headers=headers)
    soup = BeautifulSoup(r.text, "html.parser")
    data = soup.find("div",{"class":"price price-final"})
    response = session.get("https://www.yapo.cl/vi/74410346.htm?ca=15_s".format(data=data))
    soup = BeautifulSoup(response.text, "html.parser")
    print(data.text)

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2018-10-15
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多