簡體   English   中英

Python,Selenium,CSV和UTF-8(法語)字符

[英]Python, Selenium, CSV, and UTF-8 (French) characters

我有一個包含法語單詞(例如“immédiatement”)的CSV文件。 我正在使用Python和Selenium Webdriver將這些單詞寫入文本字段。 基本上,使用必需的Selenium軟件包和csv:

  • 啟動硒並轉到正確的區域。
  • 打開CSV文件。
  • 對於每一行:
    • 獲取包含法語單詞的單元格。
    • 將該單詞寫在文本區域中。

問題:

“ UnicodeDecodeError:'utf8'編解碼器無法解碼位置3的字節0x82:無效的起始字節”

我試過了:

  • 在文件頂部聲明“ coding:utf-8”,並將其忽略
  • 將變量設置為單元格內容后,附加.decode(“ utf-8”)
  • 一旦我為單元格的內容設置了變量,就添加.encode(“ utf-8”)

沒愛。

(我無法將其設置為“忽略”或“替換”,因為我需要實際輸入該單詞。它似乎不是Selenium本身,因為當我將列表直接放在腳本中時,鍵入就可以了(我可以將其作為腳本中的字典輸入,但是耶穌, 為什么 。)

我想念什么?

[編輯]樣本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()

經過幾個小時的嘗試,我找到了一種方法,但是我不得不完全離開csv.reader。 您面臨的問題是經典的python字節字符串vs unicode字符串問題。 我還不太熟練使用python unicode和字節字符串,並且csv.reader在后台使用了某種我無法弄清楚的編碼。 然而:

from selenium.webdriver.chrome.webdriver import WebDriver
import io

csvdoc = "your_path/file.csv"

driver = WebDriver("your_path/chromedriver.exe")
driver.get("http://google.com")
element = driver.find_element_by_id("lst-ib")
with io.open(csvdoc, 'r') as csvfile:
    csvcontent = csvfile.read()
    print(csvcontent)
    for l in csvcontent.splitlines():
        line = l.split(',')
        element.send_keys(line[0])
        element.send_keys(line[1])
        element.send_keys(line[2])

當我選擇不使用csv.reader來獲取文件的內容時,便能夠使用可預測的String。 然后,只需將其拆分成正確的循環即可。 最后,我的字符串被硒send_keys()方法接受。

我也將open() as更改為io.open() as 最初這是為了能夠將編碼值作為第三個參數(我正在使用python 2.7)。 當我刪除第三個參數時,腳本仍然有效,但是刪除了io. 不工作。

我知道這是解決您的問題的原始方法,但至少可以奏效,目前,這是唯一的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM