Search code examples
pythonpython-requests-html

Executing Javascrpt after requests-html render


How to execute a javascript after calling its render() function? The documentation just says to call it and no further explanation how to do the rest, for example clicking a button. Here is the original code from the documentation:

>>> r = session.get('http://python-requests.org/')

>>> r.html.render()

>>> r.html.search('Python 2 will retire in only {months} months!')['months']
'<time>25</time>'

How can I find a button and execute the click event of it? I know how to do it in selenium. But it's not clear what to do here.


Solution

  • click() function is not yet available, you can follow this issue for update. Current solution is to inject the script and pass to .render()

    r = session.get("http://....")
    
    script = """
        () => {
           const button = document.querySelector("button");
           if(button) {
             button.click()
           }
        }
    """
    
    r.html.render(script=script)