So I have recently found out that you can execute JavaScript in browsers using Selenium in Python. I have a function that returns a list of items that looks like this:
var elements = document.getElementsByClassName('example');
elements = [...elements].map(el => el.children[0].children[0].getAttribute('href').toString());
Executing this in the Browser console gets you a list of all href-s of the grandchildren of every element which has a class of example.
Is it possible to do something like this using either direct Javascript-calls or built-in Selenium functions?
To extract all the href values to python you could try the following:
elems = driver.find_elements_by_css_selector(".example > *:first-of-type > *:first-of-type[href]")
links = [elem.get_attribute('href') for elem in elems]
Or, if you just want to call a js code on the browser in a single-line call:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("<your_website>")
driver.execute_script("console.log('myElements', Array.from(document.getElementsByClassName('example')).map(elm => elm.firstElementChild.firstElementChild.getAttribute('href').toString()))")
to get the children's href in native Selenium, equivalent to your code, it'd be something like this :
elems = driver.find_elements_by_xpath("example xpath")
for ele in elems:
link = ele.find_element_by_xpath(".//child::*").get_attribute('href')
print(link)