Python:将二进制文件打印为字符串

标签 python

我有一个爬虫程序可以解析给定站点的 HMTL 并打印部分源代码。这是我的脚本:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
import urllib.request
import re

class Crawler:

    headers = {'User-Agent' : 'Mozilla/5.0'}
    keyword = 'arroz'

    def extra(self):
        url = "http://buscando.extra.com.br/search?w=" + self.keyword
        r = requests.head(url, allow_redirects=True)    
        print(r.url)
        html = urllib.request.urlopen(urllib.request.Request(url, None, self.headers)).read()
        soup = BeautifulSoup(html, 'html.parser')
        return soup.encode('utf-8')

    def __init__(self):
        extra = self.extra()
        print(extra)

Crawler()

我的代码工作正常,但它在值之前打印带有烦人的 b' 的源代码。我已经尝试使用 decode('utf-8') 但它没有用。有什么想法吗?

更新

如果我不使用 encode('utf-8') 我会出现以下错误:

Traceback (most recent call last):
  File "crawler.py", line 25, in <module>
    Crawler()
  File "crawler.py", line 23, in __init__
    print(extra)
  File "c:\Python34\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2030' in position
13345: character maps to <undefined>

最佳答案

除了将 return soup.encode('utf-8') 替换为 return soup 之外,当我按照给定的方式运行您的代码时,它工作正常。我的环境:

  • 操作系统:Ubuntu 15.10
  • Python:3.4.3
  • python3 dist-packages bs4 版本:beautifulsoup4==4.3.2

这让我怀疑问题出在您的环境,而不是您的代码。您的堆栈跟踪提到 cp850.py 并且您的源正在访问 .com.br 站点 - 这让我觉得您的 shell 的默认编码可能无法处理 unicode人物。这是 cp850 - Code Page 850 的维基百科页面.

您可以检查您的终端使用的默认编码:

>>> import sys
>>> sys.stdout.encoding

我的终端响应:

'UTF-8'

我假设你的不会,这是你遇到的问题的根源。

编辑:

事实上,我可以通过以下方式准确复制您的错误:

>>> print("\u2030".encode("cp850"))

这就是问题所在 - 由于您计算机的区域设置,print 隐式转换为您系统的默认编码并引发 UnicodeDecodeError。

更新 Windows 以在命令提示符下显示 unicode 字符有点超出我的掌控范围,因此除了将您定向到 relevant question/answer 之外,我无法提供任何建议。 .

关于Python:将二进制文件打印为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458784/

相关文章:

python - 我如何在 django 中运行特定的迁移部门

Python 日志记录类型错误

python - 同一位置周围多次出现边界框

python - 如何在 pytest 中使用具有不同数据结构的不同 fixture 进行一次测试?

python - 哪些验证码解决方案可以与 App Engine 一起使用?

python - 将 requests.Session() cookie 传输到 Python 中的 selenium 网络驱动程序

python - 在电子邮件正文中附加列表或 for 循环的内容

python - 使用m1芯片在mac上安装python表

python - 最佳实践默认函数参数python

python - 如何在 matplotlib 中为一个图形设置本地 rcParams 或 rcParams