【问题标题】:Locating html elements through xpath in Selenium Python在 Selenium Python 中通过 xpath 定位 html 元素
【发布时间】:2014-01-17 21:35:58
【问题描述】:

我是 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. 访问此链接的其他可能方式是什么?

已经谢谢了!

经过我的研究:

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

【问题讨论】:

  • 我将在那里进行详细的课程。但在这里我使用的是“XPath Checker”,它能够找到特定的元素(我能够测试它)。我不明白为什么会发生这种情况?
  • @user1177636 - 如果你告诉他出了什么问题会更有帮助。
  • 哈,看来我已经对他的另一个问题发表了尖刻的评论。很公平。
  • 我不知道 x: 在 XPath 中是什么意思。
  • 使用 CSS!它更快更干净!

标签: python selenium xpath


【解决方案1】:

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

【讨论】:

  • 我相信这是解决方案,因为我今天也遇到了同样的问题,只需删除命名空间“x:”即可解决。但是,我不知道为什么 XPath Checker 给出的 XPath 有这个“x”的东西。
【解决方案2】:

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

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

无论如何,我建议您下载 firebug 和 firepath for firefox,并通过此工具检索您需要的 xpath

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多