首页 > 解决方案 > 带有正则表达式的 Python beautifulsoup

问题描述

我正在尝试poster在 html 页面上获取以下 JSON 对象的值。我可以在 PHP 中执行此操作,但在 python 中遇到问题

HTML 页面示例

  <script>
        (function(window, sabaPlayer) {
            var options = JSON.parse('{"poster":"https:\/\/static.cdn.asset.example.com\/avt\/14ewrwer33-6793-b__35454e466.jpg","plugins":{"sabaPlayerPlugin":{"uuid":"ulF31","duration":366,"logo":"",

PHP (works) 这是返回的https://static.cdn.asset.example.com/avt/14ewrwer33-6793-b__35454e466.jpg

$txt = $html;

$matches = [];
preg_match('/JSON.parse\(\'(.*)\'\)/iu', $txt, $matches);
$parsed = json_decode($matches[1]);

$poster = $parsed->poster;

使用 Python 不会返回任何内容。有page.content

soup = BeautifulSoup(page.content, 'html.parser')
test = soup.find_all(re.compile("/JSON.parse\(\'(.*)\'\)/iu"))
print(test)

我该如何解决?

标签: python

解决方案


soup.find_all(re.compile("/JSON.parse\(\'(.*)\'\)/iu"))搜索与正则表达式匹配的标签。显然没有。

另请注意,您没有在 Python 中使用正确的正则表达式语法。不需要前导/(它实际上是正则表达式的一部分),标志不应该是正则表达式的一部分。

您有 2 个选项:

  • 首先找到所有script标签,然后尝试匹配正则表达式每个标签的文本:

    string = ''' <script>
        (function(window, sabaPlayer) {
            var options = JSON.parse('{"poster":"a poster"}')
            }
            </script>'''
    
    from bs4 import BeautifulSoup
    import json
    import re
    
    soup = BeautifulSoup(string, 'html.parser')
    
    script_tags = soup.find_all('script')
    for tag in script_tags:
        match = re.search("JSON.parse\(\'(.*)\'\)", tag.text)
        if match:
            print(json.loads(match.group(1))['poster'])
    # a poster
    
  • 在整个页面内容上使用正则表达式,不需要 beautifulsoup。我认为这是不太可取的选择。

    string = ''' <script>
    (function(window, sabaPlayer) {
        var options = JSON.parse('{"poster":"a poster"}')
        }
        </script>'''
    
    import re
    import json
    
    match = re.search("JSON.parse\(\'(.*)\'\)", string)
    if match:
        print(json.loads(match.group(1))['poster'])
    # a poster
    

推荐阅读