我有一个爬行程序,它解析给定站点的HMTL并打印部分源代码。这里是我的脚本:Python:打印二进制字符串
#!/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')
,但它没有奏效。有任何想法吗?
UPDATE
如果我不使用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>
那么你为什么在这里使用'encode'?尝试“返回汤”。 –
没有这个它返回以下错误: '回溯(最近通话最后一个): 文件 “crawler.py” 25行,在 爬虫() 文件 “crawler.py” 23行,在__init__ 打印(额外) 文件“c:\ Python34 \ lib \ encodings \ cp850.py”,第19行,编码为 return codecs.charmap_encode(input,self。错误,encoding_map)[0] UnicodeEncodeError:'charmap'编解码器不能编码字符'\ u2030'在位置 13345:字符映射到' –
bodruk
'bytes'在Python 3中没有'encode'方法你开始一个字符串,并将其转换为字节字符串 – chucksmash