I am using this JavaScript to validate a form:
<script type="text/javascript">
function validateForm()
{
var a=document.forms["orderform"]["Name"].value;
var b=document.forms["orderform"]["Street"].value;
var c=document.forms["orderform"]["ZIP"].value;
var d=document.forms["orderform"]["City"].value;
var e=document.forms["orderform"]["PhoneNumber"].value;
if (
a==null || a=="" ||
b==null || b=="" ||
c==null || c=="" ||
d==null || d=="" ||
e==null || e==""
)
{alert("Please fill all the required fields.");
return false;
}
}
</script>
I am trying to capture the alert text using BeatifulSoup:
import re
from bs4 import BeautifulSoup
with open("index.html") as fp:
soup = BeautifulSoup(fp, "lxml")
for script in soup.find_all(re.compile("(?<=alert\(\").+(?=\")")):
print(script)
This does not return anything. This is based on the example given in the BS documentation under 'A regular expression' to find tag names starting with a 'b':
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
# body
# b
but I seem to be unable to find the equivalent to 'print(tag.name)' that would print the alert text. Or am I completely on the wrong track? Any help is much appreciated.
Edit: I tried:
pattern = re.compile("(?<=alert\(\").+(?=\")"))
for script in soup.find_all ('script'):
print(script.pattern)
This returns "None".
Running over the all html data will not work. First you need to extract the script data then you can easily parse the alert text.
import re
from bs4 import BeautifulSoup
with open("index.html") as fp:
soup = BeautifulSoup(fp, "lxml")
script = soup.find("script").extract()
# find all alert text
alert = re.findall(r'(?<=alert\(\").+(?=\")', script.text)
print(alert)
Output:
['Please fill all the required fields.']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With