我有一个包含法语单词的CSV文件,例如“immédiatement”。我正在使用Python和Selenium Webdriver将这些单词写入文本字段。基本上,使用所需的Selenium包加上csv:
问题:
“UnicodeDecodeError:'utf8'编解码器无法解码位置3中的字节0x82:无效的起始字节”
我试过了:
没有爱。
(我无法将其设置为“忽略”或“替换”,因为我需要实际输入单词。它似乎不是Selenium本身,因为当我将列表直接放在脚本中时,打字很好。(我可以把它作为脚本中的dict,但耶稣,为什么。)
我错过了什么?
[edit] CSV内容示例:
3351,Payé/Effectué,Link1
45922,Plannifié,Link1
3693,Honoraires par Produit,Link2
广义代码:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import unittest, time, re, csv
csvdoc = "C:\path\to\sample.csv"
class Translations(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://baseURL.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_translations(self):
driver = self.driver
driver.get(self.base_url + "login")
driver.find_element_by_id("txtUsername").clear()
driver.find_element_by_id("txtUsername").send_keys("username")
driver.find_element_by_id("txtPassword").clear()
driver.find_element_by_id("txtPassword").send_keys("password")
driver.find_element_by_id("btnSubmit").click()
# Navigate to the correct area.
# - code goes here -
# Open the file and get started.
with open(csvdoc, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in csvreader:
elmID = row[0]
phrase = row[1]
arealink = row[2]
driver.find_element_by_xpath("//a[text()='%s']" % arealink).click()
time.sleep(1)
driver.find_element_by_id(elmID).clear()
driver.find_element_by_id(elmID).send_keys(phrase)
driver.find_element_by_id("btnSavePhrase").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
答案 0 :(得分:0)
经过几个小时的尝试,我找到了一种方法,但我不得不完全离开csv.reader。您面临的问题是经典的python byte-string-vs unicode-string问题。我还不能熟练使用python unicode和字节字符串,而csv.reader在后台使用了某种我无法弄清楚的编码。但是:
csv.reader
当我选择在没有send_keys()
的情况下获取文件的内容时,我能够获得可预测的字符串。然后,这只是在正确的循环中分裂它的问题。最后,我的字符串被selenium open() as
- 方法接受。
我还将io.open() as
更改为io.
。这最初是为了能够包含一个编码值作为第三个参数(我使用的是python 2.7)。当我删除第三个参数时,脚本仍然有效,但删除(^|www|http://|https://)+(\.)?(.+?)\.
不起作用。
我知道这是解决问题的一种原始方式,但至少它是有效的,现在它是唯一的答案。