Christ Adam
Christ Adam

Reputation: 31

How to retrieve javascript variable in HTML script using Python Regex?

<script>
    function foo() {
        var bar = 'thisisvalue';
    }   
</script>

Hi all, I have this function in script tag and I want to get the value of var bar by using Python regular expression. Can anyone help me with this. Thanks

Upvotes: 0

Views: 853

Answers (2)

John Gordon
John Gordon

Reputation: 33335

for line in html:
     if 'var bar =' in line:
         thisisvalue = line.split("'")[1]

Upvotes: 0

Jon Sorenson
Jon Sorenson

Reputation: 136

The pattern I always use in python is this:

import re
SEARCHER = re.compile( *regex with captured groups* )

...later, in a loop over lines...

  search = SEARCHER.search(line)
  if search:
     value = search.group(1)

In your particular case it would be something like this:

import re
VARBAR_SEARCHER = re.compile(r"var bar = '([^']*)'")

...

  search = VARBAR_SEARCHER.search(line)
  if search:
     value = search.group(1)

This omits the single quotes from the value. If you wanted those in there you could modify the regular expression.

Upvotes: 1

Related Questions