python - 如何使用 BeautifulSoup 获得“id”值?
问题描述
如何id
从以下 HTML 中获取值?
print(type(author_info))
output: <class 'bs4.element.Tag'>
print(author_info)
output: <script data-mru-fragment="models/user/journal" type="text/plain">
{
"name": "on-line журнал РАЗНЫЕ ЛЮДИ",
"id": "-2812448",
"auId": "8911662942803793376",
"email": "rl_journal",
"dir": "/community/rl_journal/",
"isVip": false,
"isCommunity": true,
"isVideoChannel": false
}
解决方案
您看到的数据是JSONdict
格式,您可以使用内置模块将其转换为 Python 字典 ( ) json
,然后访问id
密钥:
import json
from bs4 import BeautifulSoup
script_doc = """
<script data-mru-fragment="models/user/journal" type="text/plain">
{
"name": "on-line журнал РАЗНЫЕ ЛЮДИ",
"id": "-2812448",
"auId": "8911662942803793376",
"email": "rl_journal",
"dir": "/community/rl_journal/",
"isVip": false,
"isCommunity": true,
"isVideoChannel": false
}</script>"""
soup = BeautifulSoup(script_doc, "html.parser")
json_data = json.loads(soup.find("script").string)
# With your example using `author_info`:
# json_data = json.loads(author_info.string)
输出:
>>> print(type(json_data))
<class 'dict'>
>>> print(json_data["id"])
-2812448
推荐阅读
- python - 循环遍历行时记住上一行
- python - 从 Django 中的自定义表单/表单集创建模型对象
- node.js - 如何在 nodejs 上使用 DynamoDb 测试等待/异步?
- php - 将内容放入带有文本的文件中
- swift - 在 Swift 4 中计算时差
- reactjs - 以太坊 - Embark 控制台方法调用所有返回为未定义
- batch-file - 检查远程进程并在存在时“杀死”它的脚本
- wijmo - 如何使用 wijmo flex 网格从后面冻结列?
- c++ - 这个程序中的 16 位数学是否调用了未定义的行为?
- teamcity - 导入特定绑定文件时 BizTalk 2016 挂起