我正在尝试使用Selenium和Python自动化网页。我使用了' xpath checker - https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/'在firefox中编写以下代码。
Selenium-Python代码:
def create_user():
#Click 'Administration'
mydriver.find_element_by_xpath("//*[@id('main-navigation')/x:li[5]/x:a").click()
mydriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
mydriver.find_element_by_xpath("//*[@id('main-navigation')/x:li[5]/x:ul/x:li[1]/x:ul[2]/x:li[2]/x:a").click()
mydriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
mydriver.find_element_by_xpath("//*[@id('accordion')/x:li[2]/x:a").click()
mydriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
create_user()
如果我执行上述操作,我会收到以下错误:
InvalidSelectorException: Message: The given selector //*[@id('main-navigation')
/x:li[5]/x:a 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('main-navigation')/x:li[5]/x:a because of the following error:
SyntaxError: The expression is not a legal expression.
Stacktrace:
at FirefoxDriver.annotateInvalidSelectorError_ (file:///c:/users/admin/appda
ta/local/temp/2/tmpgchoem/extensions/fxdriver@googlecode.com/components/driver-c
omponent.js:10744)
at FirefoxDriver.prototype.findElementInternal_ (file:///c:/users/admin/appd
ata/local/temp/2/tmpgchoem/extensions/fxdriver@googlecode.com/components/driver-
component.js:10775)
at FirefoxDriver.prototype.findElement (file:///c:/users/admin/appdata/local
/temp/2/tmpgchoem/extensions/fxdriver@googlecode.com/components/driver-component
.js:10779)
at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/admin/appda
ta/local/temp/2/tmpgchoem/extensions/fxdriver@googlecode.com/components/command-
processor.js:12661)
at DelayedCommand.prototype.executeInternal_ (file:///c:/users/admin/appdata
/local/temp/2/tmpgchoem/extensions/fxdriver@googlecode.com/components/command-pr
ocessor.js:12666)
at DelayedCommand.prototype.execute/< (file:///c:/users/admin/appdata/local/
temp/2/tmpgchoem/extensions/fxdriver@googlecode.com/components/command-processor
.js:12608)
有人可以建议修改此代码。
答案 0 :(得分:0)
您需要额外的]
来关闭[@id=...]
阻止。所以试试
mydriver.find_element_by_xpath("//*[@id='main-navigation']/x:li[5]/x:a").click()
mydriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
mydriver.find_element_by_xpath("//*[@id='main-navigation']/x:li[5]/x:ul/x:li[1]/x:ul[2]/x:li[2]/x:a").click()
mydriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
mydriver.find_element_by_xpath("//*[@id='accordion']/x:li[2]/x:a").click()
mydriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);