from import : 从车里把矿泉水拿出来,给我
import : 把车给我
import datetime
print(datetime.datetime.now())
是引入整个datetime包
from datetime import datetime
print(datetime.now())
是只引入datetime包里的datetime类
所以import之后前者是datetime这个包可见 后者是datetime.datetime这个类可见
2. ImportError: No module named 'cookielib'1
Python3中,改成 import http.cookiejar,然后方法里也改成 http.cookiejar,查找替换就行
3. NameError: name 'raw_input' is not defined
在版本3中已经用input()替换
4. Import error: No module name urllib
from urllib.request import urlopen
5. ImportError: No module named urllib2
Python 3中urllib2用urllib.request替代
6、TypeError: write() argument must be str, not bytes
文件打开的方式有问题。
之前文件打开的语句是:
f=open("list.pkl","w+")
然后使用二进制方式打开就没有这个问题:
f=open("list_account.pkl","wb+")
产生问题的原因是因为pickle存储方式默认是二进制方式
写文件处 open(filename, 'w').write 应该写为 open(filename, 'wb').write
8、TabError: Inconsistent use of tabs and spaces in indentation
这个错误是说你用了tab键作缩进了
在python里不用大括号来区分程序块,用缩进
所以缩进很重要
你把tab都换成空格就好了
3.0现在的参数更改了,现在读取的是bytes-like的,但参数要求是chart-like的,找了一下,加了个编码:
data = data.decode('GBK')
在与正则使用前,就可以正常使用了..
去找找你所调用的函数的返回的值的类型,是否和返回值所赋值的变量的类型,两者是否匹配。
11、module 'urllib' has no attribute 'urlencode'
Python3的话,包内部的代码结构貌似变化了,要用urllib.parse.urlencode()来调用才对。
12、python3.x执行post请求时报错“POST data should be bytes or an iterable of bytes...”的解决方法
在urlencode语句后加encode(encoding='UTF8')
eg:
params = urllib.parse.urlencode({'userid':'381fccbd776c4deb'}).encode(encoding='UTF8')
问题解决
首行增加,已测试可用。
# coding=gbk
程序中出现中文,运行的时候出现如下错误:
SyntaxError: Non-UTF-8 code starting with 'xc1' in file C:...xxx.py on line 8, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
导致出错的根源就是编码问题。
解决方案是:
在程序最上面加上:
# coding=gbk搜索
这样程序就可以正常运行了。
14、使用 Sublime 工具时报Decode error - output not utf-8解决办法
打开Python.sublime-build文件,并添加"encoding":"cp936"这一行,保存即可
{
"cmd": ["python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"encoding":"cp936"
}
Python.sublime-build文件存放地址:
C:\Users\用户名\AppData\Roaming\Sublime Text 2\Packages\Python
实在找不到的话可以这样来查找:
tools->build system -> New Build System
此时会打开一个新文件,不用输入内容,直接保存,看看保存到哪里去了吧.
15、安装scrapy时报错:[twisted] CRITICAL: Unhandled error in Deferred:
16、爬取链接时,urlopen().read()后,返回的是b'\x1f\x8b\x08\x00\x00\x00\x00\。。。
解决思路:
1、刚开始尝试了bytes转Str类型的各种方法,都不起作用,报错
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
2、突然发现python有个第三方包叫chardet,它可以自动帮你识别出网页的编码
import chardet
import urllib2
#可根据需要,选择不同的数据
TestData = urllib2.urlopen('http://www.baidu.com/').read()
print chardet.detect(TestData)
准确的判断编码方式是utf-8.
3、我测试后,返回的编码却为这种None:
{'encoding': None, 'confidence': 0.0}
原来是这个页面的编码问题,该页面返回的是gzip编码,实际上每次应该判断页面信息的'Content-Encoding'是否为'gzip'。
urllib支持gzip页面自动解压而urllib2不支持。 所以对于这种页面, 先解压再read:
try:
response = urllib2.urlopen(self.url, timeout = self.timeout)
if response.info().get('Content-Encoding', "") == 'gzip':
buf = StringIO.StringIO(response.read())
f = gzip.GzipFile(fileobj=buf)
content = f.read()
else:
content = response.read()
content = self.enc_dec(content)
return content
except socket.timeout:
log.warn("Timeout in fetching %s" % self.url)
方法2:
def getUrlContent(url):
#返回页面内容
doc = urllib.request.urlopen(url).read()
#解码
try:
html=gzip.decompress(doc).decode("utf-8")
except:
html=doc.decode("utf-8")
return html
自己的解决方法是在请求时,将header中的
'Accept-Encoding':'gzip, deflate, sdch', 注释掉即可获取到正常的bytes数据
然后自己再次识别编码,结果为:{'encoding': 'utf-8', 'confidence': 0.99}
最后再bytes转换为 str,即可获得完整可识别的HTML代码。
==============================================================================
解压:
def ungzip(data):
try:
print('正在解压.....')
print(data)
data = gzip.decompress(data)
print('解压完毕!')
except:
print('未经压缩, 无需解压')
return data
结果:
正在解压.....
b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x14\xcaM\x0e@0\x10\x06\xd0\xbb|kii\x98xc7!\x82\x7fU\x00\x00\x00"
解压完毕!
b'{"status":"loginok","msg":"\\u767b\\u9646\\u6210\\u529f"}'
18、python getaddrinfo failed
HOST="" 中间没有空格
19、数据转换:
将b'{"status":"ok","total":"36","data":[{"id":"115878","uid":"3364","type":"9","pay":"\\u7b7e\\u5230\\u7ea2\\u5305"...}]}'
转为{"status":"ok","total":"36","data":[{"id":"115878","uid":"3364","type":"9","pay":"\u7b7e\u5230\u7ea2\u5305"...}]}
op = signsession.get(url)
#print(op.content)
data = op.content.decode()