You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遇到Unicode编码错误如何写入文件?使用bs4爬虫报错求助

问题解决方案

一、Unicode编码错误的文件写入处理

遇到Unicode编码错误时,可通过以下方式处理文件写入:

  • 直接指定文件编码为utf-8,同时配置错误处理策略:
    # 忽略无法编码的字符
    with open("output.txt", "w", encoding="utf-8", errors="ignore") as f:
        f.write(content)
    
    # 将无法编码的字符替换为?
    with open("output.txt", "w", encoding="utf-8", errors="replace") as f:
        f.write(content)
    
  • 先将内容转为字节流再写入,适合精准控制编码场景:
    with open("output.txt", "wb") as f:
        f.write(content.encode("utf-8", errors="ignore"))
    

二、bs4爬取的报错处理

从报错信息来看,触发了AttributeError: 'NoneType' object has no attribute 'text',本质是你调用text属性的对象为None,说明bs4未找到目标HTML元素。解决方法:

  • 先判断元素是否存在,再调用属性:
    from bs4 import BeautifulSoup
    import requests
    
    resp = requests.get("目标网页URL")
    soup = BeautifulSoup(resp.text, "html.parser")
    target_elem = soup.find("目标标签", attrs={"属性名": "属性值"})
    # 先校验元素是否存在
    if target_elem:
        content = target_elem.text.strip()
    else:
        content = "未定位到目标元素"
    
  • 核对选择器(标签名、属性)是否匹配当前网页结构,若目标元素是JS动态加载的,需改用Selenium等工具获取渲染后的完整HTML

内容的提问来源于stack exchange,提问作者ants

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:17:03