javascript - 使用 BeautifulSoup 捕获 JavaScript 警报文本

标签 javascript python beautifulsoup

我正在使用这个 JavaScript 来验证表单:

<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>

我正在尝试使用 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)

这不会返回任何东西。这是基于 BS 文档中“A regular expression”下给出的示例,以查找以“b”开头的标签名称:

import re
for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
# body
# b

但我似乎无法找到与打印警报文本的“print(tag.name)”等价的方法。还是我完全走错了路?非常感谢任何帮助。

编辑: 我试过:

pattern = re.compile("(?<=alert\(\").+(?=\")"))
for script in soup.find_all ('script'):
  print(script.pattern)

这将返回“无”。

最佳答案

遍历所有 html 数据将不起作用。首先,您需要提取脚本 数据,然后您可以轻松地解析alert 文本。

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)

输出:

['Please fill all the required fields.']

关于javascript - 使用 BeautifulSoup 捕获 JavaScript 警报文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948405/

相关文章:

python - Beautifulsoup 从 Google 专利搜索下载所有 .zip 文件

javascript - 如果变量为真,不显示警报? JavaScript

javascript - chrome javascript内存分析器中的系统对象是什么

javascript - 将输入类型=日期值传递给日期函数以获得特定格式

python - 将权重从一个 Conv2D 层复制到另一层

php - python调用命令问题

python - 使用请求和BeautifulSoup获取Youtube视频标题有时会出错,有时会起作用(Python)

javascript - 谷歌地图有时无法加载

python - numpy数组遍历的优化

python - urllib2/requests 不显示网页的 iframe