程序目标是打开百度并搜索相关信息,代码如下:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://www.baidu.com/')
browser.find_element_by_id('kw').send_keys('哈哈哈哈')
结果报错:
Traceback (most recent call last):
File "D:/python_work/web自动化/测试.py", line 5, in <module>
browser.find_element_by_id('kw').send_keys('哈哈哈哈')
File "D:\python\lib\site-packages\selenium\webdriver\remote\webelement.py", line 477, in send_keys
self._execute(Command.SEND_KEYS_TO_ELEMENT,
File "D:\python\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "D:\python\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 319, in execute
response = self.command_executor.execute(driver_command, params)
File "D:\python\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 374, in execute
return self._request(command_info[0], url, body=data)
File "D:\python\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 397, in _request
resp = self._conn.request(method, url, body=body, headers=headers)
File "D:\python\lib\site-packages\urllib3\request.py", line 79, in request
return self.request_encode_body(
File "D:\python\lib\site-packages\urllib3\request.py", line 171, in request_encode_body
return self.urlopen(method, url, **extra_kw)
File "D:\python\lib\site-packages\urllib3\poolmanager.py", line 336, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "D:\python\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
httplib_response = self._make_request(
File "D:\python\lib\site-packages\urllib3\connectionpool.py", line 392, in _make_request
conn.request(method, url, **httplib_request_kw)
File "D:\python\lib\http\client.py", line 1230, in request
self._send_request(method, url, body, headers, encode_chunked)
File "D:\python\lib\http\client.py", line 1275, in _send_request
body = _encode(body, 'body')
File "D:\python\lib\http\client.py", line 160, in _encode
raise UnicodeEncodeError(
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 10-13: Body ('哈哈哈哈') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
后来把send_keys()内容改成非中文的就可以正常运行;
也试过send_keys(u'哈哈哈哈'),结果报同样的错,而且我发现我只要有中文就报这种错:
browser.find_element_by_link_text('百度一下').click()
百度了一大圈也没找到个解决方案,然后我把同样的程序拿到同事的电脑上面就可以正常运行,我只记得我的pycharm改过一个配置文件的值,但是不记得改得啥了 我试过重装pycharm依然没法解决,求助!!!!