Skip to content
Advertisement

How to pass web element from Python selenium to Java?

I am making a program that finds all the elements of a webpage with the word “Pens” and changes the text to asteriks. Here is the portion of my code I am having issues with:

current = driver.current_url

page = requests.get(current)
html = soup(page.content, 'html.parser')
occurencelist = html.find_all(id=True,string=re.compile("Pens"))

for element in occurencelist:
    driver.execute_script("document.getElementById('"+element.get('id')+"').innerHTML = '*******';")

The code only works for elements that have an ID. I would like to send the Xpath of the element but the only methods of ‘document’ are .getElementById(), .getElementByClassName(), .getElementByName(), and .getElementByTagName(). I have a function that returns the absolute xpath of an element so all I need is a way to send that to the Java script to reference.

Advertisement

Answer

elem = driver.execute_script("return document.evaluate('arguments[0]', document,null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue","//a")

you should use document.evaluate , now elem will have the webelement you need

https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement