2

How can I access a javascript variable with BeautifulSoup? I know the name of the variable

The variable is defined in a script tag:

<script>
    var variable_name = value;
</script>

For example, in the browser console I write window.variable_name and I get the value. How can I get an equivalent in Beautiful Soup?

3
  • 1
    Since you said that the "variable is defined into a script tag in the page", you can use bs4 to get the <script> tag content and then proccess the whole string to extract it's value. I'm not 100% sure this method will work because you haven't posted the url.. But in any case, take a look at this topic. Commented Apr 11, 2017 at 16:53
  • hi did you manage to solve your problem? I have similar issue and solved finding start and end of variable value but ideally would like to call the var name to make it more relaible.. Commented Aug 15, 2020 at 15:54
  • Hi @NonoLondon, I just extract the text between var variable_name and ; Commented Aug 22, 2020 at 19:39

1 Answer 1

1

You can't. BeautifulSoup is just a parser for DOM elements, it doesn't evaluate any code inside the page.

You need to "run" the page and access it while it's still "on", using, for example, Selenium, as explained in this post

Sign up to request clarification or add additional context in comments.

2 Comments

The variable is defined into a script tag in the page. I edited the question
Still, are you sure that is BeautifulSoup what you wanted, because what you will get is a text representation of variable's content if you manage to do that, what maybe won't work for you if the variable holds an object, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.