python - 使用 BeautifulSoup 查找 Javascript 变量定义
问题描述
我正在尝试在网站的 HTML(在标签中)中找到特定的变量定义,我有以下代码:
logResponse = scrape.post(url, params=logindata, headers=UA)
soup = bs(logResponse.text, 'html.parser')
x = soup.find_all('var my_post_key')
print(x)
我要查找的变量是“my_post_key”,但 soup.find_all 函数返回一个空列表 ([])。我怀疑我用错了,但我想知道如何正确地做到这一点。这是变量在页面 HTML 中的存储方式:
<script type="xxxxxxxxxxxxxxxxx-text/javascript">
var my_post_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
</script>
回顾一下,我只是想获取“xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”值。任何帮助表示赞赏。
解决方案
from bs4 import BeautifulSoup
import re
html = """
<script type="xxxxxxxxxxxxxxxxx-text/javascript">
var my_post_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
</script>
"""
soup = BeautifulSoup(html, 'html.parser')
target = soup.select_one("script").string
print(target.split('"')[1])
#Or
match = re.search(r'key = \"(.+?)\"', target).group(1)
print(match)
输出:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
推荐阅读
- c - 如何设置 VSCode 来编译具有多个文件的 C 程序?
- python - 在图像序列中生成下一帧
- flutter - 如何在 Flutter 中从 google fit 和 iOS HealthKit 获取数据
- sql - 如何在 sql 中运行 sed -i
- python - 如何编写服务器操作以更新 odoo 中的多个记录
- algorithm - 给定边缘列表时如何执行 DFS 或 BFS?
- node.js - 在回调函数中获取推送元素到猫鼬数组
- javascript - 在 React.js 中使用图像而不是单选按钮
- python - 如何将“[4,8,12,16]”传递给 rrule 参数?
- c++ - 测试函数命令行的输出