【问题标题】:Solved: selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified已解决:selenium.common.exceptions.InvalidSelectorException:消息:无效选择器:指定了无效或非法的选择器
【发布时间】:2020-05-21 19:35:17
【问题描述】:

已解决:我正在尝试制作一个随机回答 kahoot 的脚本,一切正常,但是当脚本必须单击“下一步”按钮时,我收到此错误:'selenium.common.exceptions.InvalidSelectorException:消息:无效选择器:指定了无效或非法的选择器' 我尝试搜索此错误,但没有出现与我的脚本相关的任何内容。 请帮帮我。

import random
from selenium import webdriver
driver=webdriver.Firefox()
driver.get("kahoot link")
choices= ['//*[@id="challenge-game-router"]/main/div[2]/div[1]/span', '//*[@id="challenge-game-router"]/main/div[2]/div[2]/span', '//*[@id="challenge-game-router"]/main/div[2]/div[3]', '//*[@id="challenge-game-router"]/main/div[2]/div[4]']
try:
    sleep(5)
    nickname= driver.find_element_by_name('nickname')
    nickname.send_keys(username)
    enter = driver.find_element_by_xpath('//*[@id="challenge-game-router"]/main/section/div[1]/form/button').click()
finally:
    pass


for c in range(0, 3):
    try:
        driver.implicitly_wait(20)
        choice = driver.find_element_by_xpath(random.choice(choices))
        choice.click()
        driver.implicitly_wait(20)
        next = driver.find_element_by_xpath('/html/body/div/div/div/div/main/button')
        next.click()
    finally:
        pass

【问题讨论】:

  • choices 是什么?您没有在代码中定义它。
  • @Charles 你说得对,我忘了复制那部分代码,我将对其进行编辑,谢谢

标签: python selenium


【解决方案1】:

您试图在此处按类名查找元素,但将 xpath 提供给 find_element_by_class_name 函数,这就是它抛出无效选择器异常的原因。

next = driver.find_element_by_class_name('/html/body/div/div/div/div/main/button')

您应该提供一个有效的类名或改用find_element_by_xpath

【讨论】:

  • 谢谢,但现在我收到此错误:selenium.common.exceptions.NoSuchElementException: 消息:没有这样的元素:无法找到元素:{"method":"xpath","selector" :"/html/body/div/div/div/div/main/button"}
  • 那么你可能需要更正xpath /html/body/div/div/div/div/main/button
  • 我试图检查并复制 xpath 并得到了这个:'//*[@id="challenge-game-router"]/main/button' 但我还是一样错误(是否有另一种获取 xpathes 的方法,我做错了?)
  • 好的,所以要确定你的 xpath //*[@id="challenge-game-router"]/main/button 是否正确...在检查元素查找栏中输入它,看看它是否突出显示按钮?
  • 不,没有突出显示,我怎么可能复制了错误的 xpath?
【解决方案2】:

我通过使用 Firefox 而不是 Google_Chrome 复制 Xpath 解决了我的问题。

【讨论】:

    猜你喜欢
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多