繁体   English   中英

在Selenium Python中通过xpath定位html元素

[英]Locating html elements through xpath in Selenium Python

我是Selenium的新用户,尝试访问并点击Google页面上的“图片”链接,一旦搜索了一些字符串。 但我无法做到这一点。 以下是Selenium Python:

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 Checker来获取xpath)? 2.访问此链接的其他可能方式有哪些?

谢谢!

经过我的研究:

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

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

我相信您正在尝试搜索xpath,但也许您没有传递有效值; 通常xpath的语法是这样的: .//*[@id='hdtb-msb']/div[2]/a [2] / .//*[@id='hdtb-msb']/div[2]/a

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

无论如何,我建议你为firefox下载firebug和firepath,并通过这个工具检索你需要的xpath

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM