Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium - XPATH - Searching for element by innerHTML

I'm learning Selenium and have a decent grasp of XPATH.

An issue I'm running into is that on a web page, there's an element I want to select that has a dynamically generated id and class. I had tried the following:

code = driver.find_element_by_xpath("//*[contains(@text='someUniqueString')]")

however, the element doesn't have any text. Instead it's a <code> element with JSON.

<codestyle="display: none" id="something-crazy-dynamic"> 
    {"dataIWantToGrab":{"someUniqueString":...}}
</code>

What I'm looking to do is search the innerHTML to find a unique string using XPATH but I can't find any good resources.

I've tried

driver.find_element_by_xpath("//*[contains(@innerHTML='someUniqueString')]")

but am receiving the error

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

EDIT: Below is a link to the sibling text I'm working with

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

EDIT 2: I was able to get around this, not by using Selenium but with BeautifulSoup. Not ideal, but still a solution.

soup = BeautifulSoup(driver.page_source)
codes = soup.find_all("code")
found_json = [i for i in codes if i.text.find("someUniqueString") > 0]
like image 263
shartshooter Avatar asked Mar 14 '17 04:03

shartshooter


1 Answers

You can't use XPath to match by inner HTML, but you can use it to match by 'inner text' :

//*[text()[contains(., 'someUniqueString')]]

`demo

The above XPath should return the code element since it is parent element of the target text 'someUniqueString'.

like image 178
har07 Avatar answered Oct 13 '22 07:10

har07