Selenium - XPATH - 通过innerHTML搜索元素

sha*_*ter 6 html selenium xpath beautifulsoup python-2.7

我正在学习Selenium并且对XPATH有很好的把握.

我遇到的问题是,在网页上,还有我要选择具有动态生成的元素idclass.我曾尝试过以下方法:

code = driver.find_element_by_xpath("//*[contains(@text='someUniqueString')]")
Run Code Online (Sandbox Code Playgroud)

但是,元素没有任何文本.相反,它是一个<code>带有JSON 的元素.

<codestyle="display: none" id="something-crazy-dynamic"> 
    {"dataIWantToGrab":{"someUniqueString":...}}
</code>
Run Code Online (Sandbox Code Playgroud)

我想要做的是搜索innerHTML使用XPATH找到一个唯一的字符串,但我找不到任何好的资源.

我试过了

driver.find_element_by_xpath("//*[contains(@innerHTML='someUniqueString')]")
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[contains(@innerHTML='someUniqueString')]
Run Code Online (Sandbox Code Playgroud)

编辑:下面是我正在使用的兄弟文本的链接

https://gist.github.com/anonymous/b227e59c942e7ec9f5a851a3b7ecdfc6

编辑2:我能够解决这个问题,不是使用Selenium而是使用BeautifulSoup.不理想,但仍然是一个解决方案.

soup = BeautifulSoup(driver.page_source)
codes = soup.find_all("code")
found_json = [i for i in codes if i.text.find("someUniqueString") > 0]
Run Code Online (Sandbox Code Playgroud)

har*_*r07 12

您不能使用XPath来匹配内部HTML,但您可以使用它来匹配"内部文本":

//*[text()[contains(., 'someUniqueString')]]
Run Code Online (Sandbox Code Playgroud)

`demo

上面的XPath应该返回code元素,因为它是目标文本'someUniqueString'的父元素.

  • @kmomo 你也尝试过这个答案中的 XPath 吗?`//*[text()[包含(., 'someUniqueString')]]` (2认同)