【问题标题】:How can I get the "id" value with BeautifulSoup?如何使用 BeautifulSoup 获得“id”值?
【发布时间】:2021-06-03 04:02:52
【问题描述】:

如何从以下 HTML 中获取 id 值?

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
}

【问题讨论】:

    标签: python parsing beautifulsoup key


    【解决方案1】:

    您看到的数据是JSON格式,您可以使用内置的json模块将其转换为Python字典(dict),然后访问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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2021-11-18
      • 2018-08-15
      • 2017-02-14
      • 1970-01-01
      相关资源
      最近更新 更多