在 Selenium (Python) 中使用 XPath Selector 'following-sibling::text()' [英] Using XPath Selector 'following-sibling::text()' in Selenium (Python)

查看:35
本文介绍了在 Selenium (Python) 中使用 XPath Selector 'following-sibling::text()'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Selenium(在 Python 中)从网站中提取一些信息.我一直在使用 XPath 选择元素,但在使用以下兄弟选择器时遇到了问题.HTML如下:

I'm trying to use Selenium (in Python) to extract some information from a website. I've been selecting elements with XPaths but am having trouble using the following-sibling selector. The HTML is as follows:

<span class="metadata">
    <strong>Photographer's Name: </strong>
    Ansel Adams
</span>

我可以用

In [172]: metaData = driver.find_element_by_class_name('metadata')

In [173]: metaData.find_element_by_xpath('strong').text
Out[173]: u"Photographer's Name:"

我正在尝试选择标记后的文本部分(示例中为Ansel Adams").我以为我可以使用以下兄弟选择器,但我收到以下错误:

I'm trying to select the section of text after the tag ('Ansel Adams' in the example). I assumed I could use the following-sibling selector but I receive the following error:

In [174]: metaData.find_element_by_xpath('strong/following-sibling::text()')
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (328, 0))
... [NOTE: Omitted the traceback for brevity] ...
InvalidSelectiorException: Message: u'The given selector strong/following-sibling::text() is either invalid or does not result in a WebElement. The following error occurred:\n[InvalidSelectorError] The result of the xpath expression "strong/following-sibling::text()" is: [object Text]. It should be an element.' 

关于为什么这不起作用的任何想法?

Any ideas as to why this isn't working?

推荐答案

@RossPatterson 是正确的.问题是文本'Ansel Adams' 不是WebElement,所以你不能使用find_elementfind_elements.如果您将 HTML 更改为

@RossPatterson is correct. The trouble is that the text 'Ansel Adams' is not a WebElement, so you cannot use find_element or find_elements. If you change your HTML to

<span class="metadata">
    <strong>Photographer's Name: </strong>
    <strong>Ansel Adams</strong>
</span>

然后 find_element_by_xpath('strong/following-sibling::*[1]').text 返回 'Ansel Adams'.

then find_element_by_xpath('strong/following-sibling::*[1]').text returns 'Ansel Adams'.

这篇关于在 Selenium (Python) 中使用 XPath Selector 'following-sibling::text()'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆