lionhua0809 发表于 2016-9-22 17:54:17

python+selenium 编码问题

#coding=utf-8

from selenium import webdriver
from time import sleep

def login():
        driver.switch_to_frame("login_frame")
        driver.find_element_by_id("u").clear()
        driver.find_element_by_id("u").send_keys("username")
        driver.find_element_by_id("p").clear()
        driver.find_element_by_id("p").send_keys("password")
        driver.find_element_by_id("login_button").click()

def logout():
        driver.find_element_by_link_text("退出").click() #1
        #driver.find_element_by_xpath("//*[@id='SetInfo']/div/a").click() #2
        sleep(5)
        driver.quit()

driver = webdriver.Firefox()
driver.get("http://mail.qq.com/")
login()
logout()

运行报错:
Traceback (most recent call last):
File "mailqq.py", line 23, in <module>
    logout()
File "mailqq.py", line 15, in logout
    driver.find_element_by_link_text("退出").click()
File "D:\Python27\lib\site-packages\selenium-2.53.1-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 314, in find_element_by_link_text
    return self.find_element(by=By.LINK_TEXT, value=link_text)
File "D:\Python27\lib\site-packages\selenium-2.53.1-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 744, in find_element
    {'using': by, 'value': value})['value']
File "D:\Python27\lib\site-packages\selenium-2.53.1-py2.7.egg\selenium\webdriv
er\remote\webdriver.py", line 231, in execute
    response = self.command_executor.execute(driver_command, params)
File "D:\Python27\lib\site-packages\selenium-2.53.1-py2.7.egg\selenium\webdriv
er\remote\remote_connection.py", line 392, in execute
    data = utils.dump_json(params)
File "D:\Python27\lib\site-packages\selenium-2.53.1-py2.7.egg\selenium\webdriv
er\remote\utils.py", line 32, in dump_json
    return json.dumps(json_struct)
File "D:\Python27\lib\json\__init__.py", line 244, in dumps
    return _default_encoder.encode(obj)
File "D:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
File "D:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xcd in position 0: invalid continuation byte
我用的是UE编写的代码,默认格式是DOS,还有系统默认的编码是ASCII,请大家看看什么原因?如何解决?
还有就是我用#2的代码,运行也报错,提示找不到元素,为什么会找不到呢?
谢谢!


掉渣饼 发表于 2016-9-22 20:48:05

你在driver.find_element_by_id("login_button").click()下面加一个等待时间,试试
driver.find_element_by_id("login_button").click()
sleep(5)

掉渣饼 发表于 2016-9-22 20:54:32

你在脚本调试时,看登录时会不会出现输入验证码,如果出现的话,也有可能报错;解决方法可以手动登录时可以选择下次自动登录

若尘_51 发表于 2016-9-23 08:36:11

在中文前面需要加个u试试:
driver.find_element_by_link_text(u"退出").click()
页: [1]
查看完整版本: python+selenium 编码问题