现在我在Python中使用Selenium时遇到问题。这是我第一次使用它,所以如果我做了一些可怕的错误,请告诉我。无论如何,我希望下面的脚本点击网站上的按钮。看起来并不难,但由于某种原因它总是给我这个错误:
selenium.common.exceptions.InvalidSelectorException was unhandled by user code
Message: Message: The given selector id('panel1-7')/x:div[1]/x:button is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression id('panel1-7')/x:div[1]/x:button because of the following error:
NamespaceError: An attempt was made to create or change an object in a way which is incorrect with regard to namespaces
Stacktrace:
at FirefoxDriver.annotateInvalidSelectorError_ (file:///C:/Users/USER/AppData/Local/Temp/tmpd47h5z77/extensions/fxdriver@googlecode.com/components/driver-component.js:10744)
at FirefoxDriver.prototype.findElementInternal_ (file:///C:/Users/USER/AppData/Local/Temp/tmpd47h5z77/extensions/fxdriver@googlecode.com/components/driver-component.js:10775)
at FirefoxDriver.prototype.findElement (file:///C:/Users/USER/AppData/Local/Temp/tmpd47h5z77/extensions/fxdriver@googlecode.com/components/driver-component.js:10779)
at DelayedCommand.prototype.executeInternal_/h (file:///C:/Users/USER/AppData/Local/Temp/tmpd47h5z77/extensions/fxdriver@googlecode.com/components/command-processor.js:12661)
at DelayedCommand.prototype.executeInternal_ (file:///C:/Users/USER/AppData/Local/Temp/tmpd47h5z77/extensions/fxdriver@googlecode.com/components/command-processor.js:12666)
at DelayedCommand.prototype.execute/< (file:///C:/Users/USER/AppData/Local/Temp/tmpd47h5z77/extensions/fxdriver@googlecode.com/components/command-processor.js:12608)
以下是我正在使用的代码
##Import Modules
##
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import unittest
import time
##Initialize and Define Variables
##
driver = webdriver.Firefox()
##Open up webpage
driver.get("http://PretendThisIsTheTargetWebsitePlease.com")
RedButtonXpath = "id('panel1-7')/x:div[1]/x:button"
BlackButtonXpath = "id('panel8-14')/x:div[1]/x:button"
GreenButtonXpath = "id('panel0-0')/x:div[1]/x:button"
RedButtonFieldElement = WebDriverWait(driver, 2).until(lambda driver: driver.find_element_by_xpath(RedButtonXpath))
BlackButtonFieldElement = WebDriverWait(driver, 2).until(lambda driver: driver.find_element_by_xpath(BlackButtonXpath))
GreenButtonFieldElement = WebDriverWait(driver, 2).until(lambda driver: driver.find_element_by_xpath(GreenButtonXpath))
##Main Loop
##
input = input("Generic answer here please! :D >>> ")
由于隐私原因,我更改了我正在使用的网站,但据我所知,实际的XPath不是问题所在。
(另外,如果您发现任何方法可以加快速度或使脚本以任何方式提高效率,请告诉我。)
答案 0 :(得分:1)
您的XPath表达式不正确。它们包含命名空间&#34; x&#34; (我不知道为什么你把这个&#34; x&#34;放在表达式中)。所以解决方案就是删除&#34; x&#34;来自您的XPath表达式。见下文:
RedButtonXpath = "id('panel1-7')/div[1]/button"
BlackButtonXpath = "id('panel8-14')/div[1]/button"
GreenButtonXpath = "id('panel0-0')/div[1]/button"