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]
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With