【问题标题】:Regex Not Matching Pattern from BeautifulSoup results来自 BeautifulSoup 结果的正则表达式不匹配模式
【发布时间】:2021-10-22 02:24:01
【问题描述】:

我正在尝试解析一些 HTML 以查找 RegEx。当我使用在线工具来验证我的正则表达式时,它可以正常工作。它找到了价值。但是,当我将 BeautifulSoup 与 RegEx 一起使用时,模式无法找到表达式。

我正在寻找这些数据:/some/path/to/file?accountTransactionID=f2448439-ec25-4a61-a6f4-4c6fa0767f19&accountNumber=123456&searchValue=ABC123&isActiveHistory=True

从这一行开始:

 var url = '/some/path/to/file?accountTransactionID=f2448439-ec25-4a61-a6f4-4c6fa0767f19&accountNumber=123456&searchValue=ABC123&isActiveHistory=True'

在下面的演示 html 中。

这是我正在使用的 Python 脚本。我已经使用了几个 SO 问题,包括这个 one,但没有成功。

如果我使用soup = BeautifulSoup(fp, 'html.parser').find_all(string=PATTERN),那么脚本的全文已存储在一个数组中。我尝试循环遍历数组以再次查找文本,但它总是空的。

我做错了什么?


Python:

FILE_PATH = os.getcwd() + '/demo.html'
PATTERN = re.compile('var url = \'(.*?)\'')

with open(FILE_PATH) as fp:
    soup = BeautifulSoup(fp, 'html.parser')  # .find_all(string=PATTERN)
    data = PATTERN.match(str(soup))
    print(f'Data: {data}')
    # for script in soup:
    #     print(script)
    #     data = PATTERN.match(str(script))
    #     if data is not None:
    #         print(f'Data: {data}')
    #     else:
    #         print('NO DATA FOUND')

输出:数据:无


HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="/some/path/1"></script>
    <script src="/some/path/2"></script>
    <script src="/some/path/31"></script>
</head>
<body>
<script type="text/javascript">
        function downloadFile() {
            var readyToDownload = 'f2448439-ec25-4a61-a6f4-4c6fa0767f19';
            if (readyToDownload !== '')
            {
                var url = '/some/path/to/file?accountTransactionID=f2448439-ec25-4a61-a6f4-4c6fa0767f19&amp;accountNumber=123456&amp;searchValue=ABC123&amp;isActiveHistory=True'
                url = url.replace(/&amp;/g, "&")
                window.open(url, '_blank');
            }
        }
    </script>
</body>
</html>

【问题讨论】:

    标签: python regex web-scraping beautifulsoup


    【解决方案1】:

    BeautifulSoup 并没有为此提供太多帮助。 BeautifulSoup.find() 或 findall() 将返回包含文本的元素,在本例中为 &lt;script&gt; 元素。

    只需匹配文件中的整个文本并在模式上调用 search() 而不是 match()。 match() 函数开始匹配字符串开头的字符,因此不会找到匹配项。

    试试这个:

    with open(FILE_PATH) as fp:
        html = fp.read()
    m = PATTERN.search(html)
    if m:
        print(m.group(1))
    

    输出:

    /some/path/to/file?accountTransactionID=f2448439-ec25-4a61-a6f4-4c6fa0767f19&amp;accountNumber=123456&amp;searchValue=ABC123&amp;isActiveHistory=True
    

    【讨论】:

      猜你喜欢
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2019-06-01
      相关资源
      最近更新 更多