【问题标题】:how to encode non-english web links to use in selenium如何编码非英文网页链接以在 selenium 中使用
【发布时间】:2013-11-24 13:59:30
【问题描述】:

我正在使用以下代码从 .txt 文件中读取一些非英语(中文)文本。

f = open('C:\data\chinese.txt')
    for line in f:
        print line  # this displays the chinese characters properly in console
        currelem = d.find_element_by_xpath("//a[contains(.," + line + ")]")  # this gives error as mentioned below /

错误信息:

InvalidSelectorException: Message: u'The given selector //a[contains(.,\ufeff\'\u8054\u7edc\u6211\u4eec\'\n)] is either invalid or does not result in a WebElement

有什么办法可以解决这个问题吗?

【问题讨论】:

  • 你还没有说你用什么工具来保存文件。如果您使用的是程序,请显示您使用的方法。
  • 我在这里使用 .txt 文件。在我的问题中也添加了详细信息。谢谢。
  • 所以,chinese.txt 实际上包含原始 html 对吗?看起来每行一页..(您可能已经进行了一些预处理以删除每行中的新行字符,对吗?)
  • 我的文本文件不包含原始 html,而只是名称。例如我的文件看起来像这样(中文), ContactUs LogOut Announcement 这些是我的webapp中的链接。我想通过使用 d.find_element_by_xpath("//a[contains(.," + line + ")]") 单击这些链接,其中,当 'line' 成功解码时,它应该是 d.find_element_by_xpath( "//a[contains(.,"ContactUs")]") 而且我没有做任何预处理,因为我不使用编码技术。但是我可以看到我的 .txt 文件以 utf-8 编码类型保存。
  • 我的问题中的代码,正确地为我提供了打印语句的输出。但是,在定位元素时,它没有正确解码它,如下面的 msg 解释的那样。 //a[包含(.,\ufeff\'\u8054\u7edc\u6211\u4eec\'\n)]

标签: python file-io character-encoding selenium-webdriver


【解决方案1】:

没有看到实际的 chinese.txt,我认为您的 contains 函数代码中缺少一些 '。也许应该是这样的:

f = open('C:\data\chinese.txt')
for line in f:
    print line  # this displays the chinese characters properly in console
    currelem = d.find_element_by_xpath("//a[contains(.,'" + line + "')]")

我还看到你的链接末尾的 \n 和开头的 \ufeff。用line.strip() 抛弃他们

【讨论】:

  • 还是同样的问题!!找不到元素!! NoSuchElementException: Message: u'Unable to locate element: {"method":"xpath","selector":"//a[contains(.,\'\ufeff\u8054\u7edc\u6211\u4eec\')]" }' ;
  • @user159087 请在问题中发布您的 chinese.txt 样本。我对此感到困惑 \ufeff 。那应该是一个 utf-8 类型的空间,应该已经用 strip() 消除了。
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 2021-03-13
  • 2011-11-28
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2020-09-26
  • 2023-03-04
相关资源
最近更新 更多