Maxime De Bruyn
Maxime De Bruyn

Reputation: 919

Selenium - Extracting the onclick event target url within a script

Let's say I have a HTML page with the following element:

<script>
    function change_url(){
        window.location.href='http://www.google.com/';
    }
</script>

<button type="button" onclick="change_url()">
     Go to Google
</button>

Is there a way to get the target URL of the button without having the browser visit the URL ?

Thank you.

Upvotes: 2

Views: 2248

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193098

As per your question heading it wouldn't be possible with Selenium to get the target URL of the button without having the browser visit the URL as Selenium mocks the User Interactions initiating a Browser Instance.

Once you initiate the browser, to get the target URL which is http://www.google.com/ you can extract the page source and use split() function as per the following code block :

driver.get('https://www.your_url.co.in')
page_source = driver.page_source
text_part = page_source.split("window.location.href='")
my_url = text_part[1].split("';")
print(my_url[0])

Upvotes: 3

Related Questions