Search code examples
pythonhtmlfindall

Python code to get the content of randomly generated math calculation


I have a webapp that generates random equations and I am trying to automate the process of solving them with Python:

Can you solve the level 1?<br/><h3><div id='calc'>0 * 8</div></h3><br/>
<form action="play.php" method="post">
 <input type="text" name="res" />
 <input type="submit" value="OK">
</form>
</div>
</body>

I wrote a script to get the equation each time it is generated :

number =  re.findall('<div id='calc'> (.*)</div></h3><br/>', content)[0]

but for some reason it keeps throwing errors

    number =  re.findall('<div id='calc'> (.*)</div></h3><br/>', content)[0]
                                      ^
SyntaxError: invalid syntax

Anyone came cross this before ?


Solution

  • number =  re.findall(r"<div id='calc'> (.*)</div></h3><br/>", content)[0]
    

    this should work , you were using single quotes ' to define string and were also using unescaped single quotes in the string , this was leading to string just being interpreted as <div id= .

    In python , r"someString" represents raw string , it is more preferrable to use them while using regex search . You can read more about raw strings here