Friday, 24 January 2020

Unable to scroll some element into view while using pseudo selector within driver.execute_script()

I've created a script using selenium to grab a text generating dynamically. It is a requirement that I use selenium, so I don't wanna go for xhr in this very case. I'm trying to use pseudo selector in selenium defining explicit wait within it. As selenium doesn't support pseudo selector, as in :contains(), I used javascript command driver.execute_script() to serve the purpose.

Now, the way I tried works inconsistently as the text I wanna grab is not within the viewport. If I scroll a little down manually while the script is running, it works. Xpath is not an option here by the way.

How can I scroll the element into view while using pseudo selector within driver.execute_script()?

I've tried like [works inconsistently]:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

with webdriver.Chrome() as driver:
    wait = WebDriverWait(driver, 10)
    driver.get('https://www.nyse.com/quote/XNYS:AAN')

    item = wait.until(
        lambda driver: driver.execute_script('''return $('span:contains("AARONS")')[0];''')
    )
    print(item.text)

Expected result:

AARONS INC

PS Before marking this post as duplicate, make sure you at least read the title of the question.



from Unable to scroll some element into view while using pseudo selector within driver.execute_script()

No comments:

Post a Comment