【问题标题】:Python Selenium UnicodeEncodeErrorPython Selenium UnicodeEncodeError
【发布时间】:2016-01-23 23:25:58
【问题描述】:

我总是在 PyCharm 中编写和运行我的程序,但是当我在常规 python 中打开它时,它给了我这个错误..(它在 pycharm 中工作)

from selenium import webdriver
import time
import random

print("\n")
user_input = input("Username: ")

##########################################################
path = r"C:\Users\John\Desktop\chromedriver.exe"
driver = webdriver.Chrome(path)
##########################################################

text_file = open(user_input +  str(random.random()) + ".txt", "w")
text_file.write("GoogleSearch:\n\n")
##########################################################
print("Google results:\n")
driver.get("https://www.google.com/#q=" + user_input)
for n in range(20):
    try:
        driver.find_element_by_xpath("""//*[@id="pnnext"]/span[2]""").click()
    except: print("out of pages")
    pass
    time.sleep(2)
    posts2 = driver.find_elements_by_class_name("_Rm")
    for post2 in posts2:
        print(post2.text)
        text_file.write(post2.text + "\n\n")


print("\n")
print("Pipl results:\n\n")
text_file.write("\n\n")
text_file.write("Pipl results:\n\n")
driver.get("https://pipl.com/search/?q=" + user_input + "&l=&sloc=&in=5")
posts1 = driver.find_elements_by_class_name("line1")
for post1 in posts1:
    print(post1.text)
    text_file.write(post1.text + "\n")

time.sleep(1)
driver.close()
Traceback (most recent call last):
  File "C:\Users\John\Desktop\peopleSearchTool.py", line 32, in <module>
    print(post2.text)
  File "C:\Users\John\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u203a' in position 23: character maps to <undefined>

【问题讨论】:

标签: python python-3.x selenium


【解决方案1】:

问题的根源很可能是代码页。 PyCharm 在具有 Unicode 代码页的控制台中运行您的程序,而独立运行显然在具有代码页 437(从 1980 年代存在)的控制台中运行。 Unicode 代码页包含一个代码为 #203a 的字符,但代码页 437 没有,因为它只包含 256 个字符。

因此,为了打印包含 FF 以上代码的字符的字符串,您必须对字符串进行编码/解码或更改控制台代码页。 但是,请注意这两种方法都可能带来很多问题。

更好的选择是坚持使用 Unicode,永远不要打印到非 Unicode 控制台。

猜你喜欢
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 2012-11-06
  • 1970-01-01
  • 2018-10-02
  • 2015-08-29
相关资源
最近更新 更多