【问题标题】:Extracting content part within bs4.element.tag into json file将 bs4.element.tag 中的内容部分提取到 json 文件中
【发布时间】:2021-11-29 11:09:41
【问题描述】:

我已经获得了脚本标签中的文本,但不知道如何使用特定字典将其导入 JSON 文件。尝试了 str 的行为方式,但仍然出现错误。

import requests
import bs4
from bs4 import BeautifulSoup as BS
import html5lib
import json

url = 'https://www.economist.com/'
r = requests.get(url)

soup = BS(r.content,'html.parser')

data = soup.find('script', attrs={'type':'application/ld+json'})

print(str(json.loads(str(data)))) #Ouput: Error: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

    标签: python html json beautifulsoup


    【解决方案1】:

    这是可行的解决方案:

    import requests
    import bs4
    from bs4 import BeautifulSoup as BS
    import html5lib
    import json
    
    url = 'https://www.economist.com/'
    r = requests.get(url)
    
    soup = BS(r.content,'html.parser')
    
    all_data = soup.find_all('script', attrs={'type':'application/ld+json'})
    
    for data in all_data:
         jsn = json.loads(data.string)
         print(json.dumps(jsn, indent=4))
    

    【讨论】:

    • 哦,很好,它是正确的 =))) 非常感谢你^^
    猜你喜欢
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2019-02-05
    • 2019-12-15
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多