2014-01-17 76 views
0

我是Selenium的新手,尝试访问并单击Google页面上的“图像”链接,只要它搜索了一些字符串。但我无法做到这一点。以下是硒的Python:通过Selenium Python中的xpath查找html元素

driver = webdriver.Firefox() 
driver.get ('http://google.com') 
q = driver.find_element_by_xpath ("id('gbqfq')")  # Search text box 
q.send_keys ('Apple') 
driver.find_element_by_name ('btnG').click() 

# I am now going to access the 'Image' link through following comamnd 
driver.find_element_by_xpath ("id('hdtb_msb')/x:div[2]/x:a").click() 

误差如下:

selenium.common.exceptions.InvalidSelectorException: Message: u'The given selector id(\'hdtb_msb\')/x:div[2]/x:a is either invalid or does not result in a WebElement. The following error occurred:\nInvalidSelectorError: Unable to locate an element with the xpath expression id(\'hdtb_msb\')/x:div[2]/x:a because of the following error:\n[Exception... "An attempt was made to create or change an object in a way which is incorrect with regard to namespaces" 

我的问题:1。 为什么这个错误来(我使用XPath检查得到的XPath)? 2.什么是其他可能的方式来访问此链接?

已经谢谢了!

我的研究后:

它看起来像我必须抓住当前页面的加载手柄?请帮助我,我是全新的。

+0

我会在那里详细讲课。但是在这里我使用的是“XPath Checker”,它能够找到特定的元素(我可以测试它)。我不明白为什么会发生这种情况? –

+0

@ user1177636 - 如果你告诉他什么是错的,那将会更有帮助。 –

+1

哈,看起来我已经对他的其他问题留下了尖锐的评论。很公平。 –

回答

2

尝试删除命名空间(即X :)

+0

我相信这是解决方案,因为我今天也遇到了同样的问题,并且通过简单地删除命名空间“x:”来解决它。但是,我不知道为什么XPath Checker提供的XPath有这个“x”的东西。 – yaobin

0

我相信,你正在试图寻找的XPath,但也许你不通过一个有效的值。一般的XPath的语法,这是一个:.//*[@id='hdtb-msb']/div[2]/a

我去谷歌网页,我检查例如图像,这是它的XPath:.//*[@id='hplogo']

在任何情况下,我建议您下载萤火虫和firepath为Firefox和通过这个工具,你检索你需要的xpath

相关问题