Home > Enterprise >  Execute Javascript using Selenium in Python
Execute Javascript using Selenium in Python

Time:01-01

I'm loading a page using selenium and I want to execute this

<script>
var ep_start = $('#episode_page a.active').attr('ep_start');
var ep_end = $('#episode_page a.active').attr('ep_end');
var id = $("input#movie_id").val();
var default_ep = $("input#default_ep").val();
var alias = $("input#alias_anime").val();
loadListEpisode('#episode_page a.active',ep_start,ep_end,id,default_ep,alias);
</script>

I have no clue how to do it in python, I tried to use the full script

js = '''script'''
browser.execute_script(js)

or just loadListEpisode(...) replacing each one by its equivalent, it's not really working. The script is present on the page so maybe there's a way to directly call it. I tried to extract ep_start, ep_end,.. by hand then doing this

source = BeautifulSoup(...)
var1 = source.find(...)
...
browser.execute_script("loadEpisodeList(var1,var2,...)")

It didn't work too, I don't think it's recognizing them as variables

CodePudding user response:

If $ represents jQuery, you would first have to load it into the browser as follows if it has not already been loaded by the current page:

path_to_jquery_js = '/my_scripts/jquery.js' # for example
with open(path_to_jquery_js, 'r') as f:
    jquery_js = r.read()
browser.execute_script(jquery_js)

If you do not have jQuery stored locally, then you would have to use something like the requests module from the PyPi repository to fetch it:

import requests

jquery_url = 'https://some_domain/jquery.js' # for example
r = requests.get(jquery_url)
jquery_js = r.text
browser.execute_script(jquery_js

Then you should be able to execute the script as follows:

script = """
var ep_start = $('#episode_page a.active').attr('ep_start');
var ep_end = $('#episode_page a.active').attr('ep_end');
var id = $("input#movie_id").val();
var default_ep = $("input#default_ep").val();
var alias = $("input#alias_anime").val();
loadListEpisode('#episode_page a.active',ep_start,ep_end,id,default_ep,alias);
"""

browser.execute_script(script)

Just make sure loadListEpisode is already defined by other JavaScript that has already been loaded.

This is untested by me for obvious reasons, but give it a shot -- it should work in principle. Let me know how it goes (I am sure you will).

CodePudding user response:

You simply need to pass the script as an argument to execute_script() method as follows:

driver.execute_script("""
var ep_start = $('#episode_page a.active').attr('ep_start');
var ep_end = $('#episode_page a.active').attr('ep_end');
var id = $("input#movie_id").val();
var default_ep = $("input#default_ep").val();
var alias = $("input#alias_anime").val();
loadListEpisode('#episode_page a.active',ep_start,ep_end,id,default_ep,alias);
""")

You can find a relevant discussion in How to extract and print the final numbers using Selenium ChromeDriver and MutationObserver

  • Related