python - 带有正则表达式的 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)
我该如何解决?
解决方案
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
推荐阅读
- rest - 如何使用 Pydio Cells API 将文件/文件夹上传到 Pydio Cells
- graphql - “文件”类型的 GraphQL 错误字段“图像”必须具有子字段选择。您的意思是“图像 { ... }”吗?
- ansible - 使用 loop/with_item 构建变量列表
- python - 使用第三个过滤列从另一列添加新列
- node.js - 来自 Lambda Node JS 的多个 Dynamo DB 调用
- html - 使用正则表达式从 R 中删除不需要的 html 标签
- c# - 加载时如何将 TagBuilder 添加到 View
- java - Arrays.asList() 的运行时类是什么
- r - 使用 ggplot 在不同时间点为多个组绘制多个密度内核(面积 = 1)
- java - Gradle编译:找不到包