该代码伸向留言板,并索引/报告最高主题。使用机翼IDE,它可以正常工作,并且没有报告错误。但是,当通过命令提示符运行时,它会出错说它无法正确编码字符。这是我第一次看到这件事,还没有找到一个很好的资源来修复它。
由于它在机翼中运行良好,我不确定还要添加到哪些可以阻止此问题在命令提示中发生的代码。
import requests
from bs4 import BeautifulSoup
url = raw_input("Enter the board URL: ")
print "n"
#send the HTTP request
response = requests.get(url)
if response.status_code == 200:
#pull the content
html_content = response.content
#send the page to BeautifulSoup
html_doc = BeautifulSoup(html_content, "html.parser")
#extract topic data
topic_spider = html_doc.find_all("span",{"class":"subject"})
data = []
for topic in topic_spider:
if topic.text!='':
data.append(topic.text)
topiclist = list(dict.fromkeys(data))
topiclist.sort(reverse=False)
for item in topiclist:
print ('[*] ' + item)
机翼可以很好地运行,没有任何错误。通过CMD,在几个成功的结果之后发生以下结果:
[*] Parenting (successful result)
Traceback (most recent call last):
File "D:xxxxtopicindexer.py", line 29, in <module>
print ('[*] ' + item)
File "C:Python27libencodingscp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'u2019' in position 31: character maps to <undefined>
我注意两件事。
一个,您使用这样的打印语句
print ('[*] ' + item)
表明您正在使用Python 3.x
第二,您的CMD输出使用Python 2.7。这似乎是您的问题。在命令行而不是python filename.py
上尝试python3 filename.py
,因为这是您默认安装时的默认值。
看看这是否在其他任何事情之前解决。
确保CMD和机翼中的Python环境相同。将环境变量设置在CMD中的机翼IDE中。
看起来您的代码是在Python 3中写的,但您的默认值设置为Python 2。
在CMD中运行代码时,只需添加python3 myfile.py
而不是python myfile.py