2017-07-22 65 views
1

我原来的代码是这样的。AttributeError:模块'sys'没有属性'setdefaultencoding'

#py3.6, windows10 
import time 
from selenium import webdriver 
import codecs 
import sys 

reload(sys) 
sys.setdefaultencoding('utf-8') 

不支持重新加载。它是固定的。

Import importlib 
Importlib.reload (sys) 

但也有一个错误。

AttributeError: module 'sys' has no attribute 'setdefaultencoding'

我应该如何解决这个问题?我很感谢你的帮助。

我也附上我的整个代码。

import time 
from selenium import webdriver 
import codecs 
import sys 

reload(sys) 
sys.setdefaultencoding('utf-8') 

browser = webdriver.PhantomJS('C:\phantomjs-2.1.1-windows/bin/phantomjs') 
url = u'https://twitter.com/search?f=tweets&vertical=default&q=%EB%B0%B0%EA%B3%A0%ED%8C%8C%20since%3A2017-07-19%20until%3A2017-07-20&l=ko&src=typd&lang=ko' 

browser.get(url) 
time.sleep(1) 

body = browser.find_element_by_tag_name('body') 
browser.execute_script("window.scrollTo(0,document.body.scrollHeight);") 

start = time.time() 
for _ in range(500): 
    now = time.time() 
    browser.execute_script("window.scrollTo(0, 
    document.body.scrollHeight);") 
    print str(_) + " seconds: " + str(now - start) 
    time.sleep(0.2) 

tweets=browser.find_elements_by_class_name('tweet-text') 

with codecs.open("test.txt", "w","utf-8") as f: 
    i = 1 
    for i, tweet in enumerate(tweets): 
     data = tweet.text 
     data = data.encode('utf-8') 
     print i, ":", data 
     msg = (str(data) +'\n') 
     f.write(msg) 
     i += 1 

end = time.time() 
print(end - start) 
browser.quit() 
+0

从python 3.4开始,这个函数不再可用了。 –

+0

另外'import'和'importlib',不能大写......请仔细检查你在这里输入的内容;) –

+0

顺便说一下,后面的代码不可能在Python 3.6上运行! –

回答

2

您应该删除sys.setdefaultencoding。请注意,这一直是Python 2中的sys.setdefaultencoding的滥用。 From Python 2 documentation

sys.setdefaultencoding(name)

Set the current default string encoding used by the Unicode implementation. If name does not match any available encoding, LookupError is raised. This function is only intended to be used by the site module implementation and, where needed, by sitecustomize . Once used by the site module, it is removed from the sys module’s namespace.

New in version 2.0.

此设置8位串的编码在Python 2.自字节串具有没有编码在Python 3,和Unicode字符串(str)既没有(他们的Unicode,但与不透明内部编码),这个功能在Python 3上将毫无意义 - 有没有什么来设置默认编码。

+0

当我删除这个短语时,我得到了一个有关编码的新错误......它很伤心。 – yome

+0

@yome **什么**错误? –

+0

这并不意味着出现错误消息。 但是,所有推文都以这种方式标记为\ xeb \ xb0 \ xb0 \ xea \ xb3 \ xa0 \ xed \。 我无法解决这个问题... – yome

相关问题