开发者社区 问答 正文

Beautiful Soup HTML解析

我正在尝试使用 Beautiful Soup 从HTML中的某些类中提取文本。我已经成功获取了文本,但是其中有些异常(无法识别的字符),如下图所示。如何使用python代码解决问题,而不是手动删除这些异常。

码:

    try:
        html =requests.get(url)
    except:
        print("no conection")
    try:
        soup = BS(html.text,'html.parser')
    except:
        print("pasre error")
    print(soup.find('div',{'class':'_3WlLe clearfix'}).get_text())

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 21:42:20 498 分享 版权
1 条回答
写回答
取消 提交回答
  • 当您访问html.text时,请求会尝试确定字符编码,以便它可以正确解码从服务器接收到的原始字节。timesofindia发送的content-type头是text / html; charset = iso-8859-1,这是Requests附带的内容。字符编码几乎可以肯定是utf-8。

    您可以通过在访问html.text之前将html的encoding设置为utf-8来解决此问题:

        try:
            html =requests.get(url)
            html.encoding = 'utf-8'
        except:
            print("no conection")
        try:
            soup = BS(html.text,'html.parser')
        except:
            print("pasre error")
        print(soup.find('div',{'class':'_3WlLe clearfix'}).get_text())
    

    或将html.content解码为utf-8,然后将其传递到BS而不是html.text:

        try:
            html =requests.get(url)
        except:
            print("no conection")
        try:
            soup = BS(html.content.decode('utf-8'),'html.parser')
        except:
            print("pasre error")
        print(soup.find('div',{'class':'_3WlLe clearfix'}).get_text())
    

    我强烈建议您学习字符编码和Unicode。很容易被它绊倒。我们都去过那里。

    字符,符号和Unicode奇迹-Tom Scott和Sean Riley撰写的Computerphile

    David C. Zentgraf绝对需要每个程序员真正了解与文本一起使用的编码和字符集

    每个软件开发人员绝对,肯定必须绝对了解Unicode和字符集(无借口!)作者:Joel Spolsky

    回答来源:stackoverflow

    2020-03-23 21:42:28
    赞同 展开评论