【问题标题】:How to Extract JSON From HTML Source Code Using Regex如何使用正则表达式从 HTML 源代码中提取 JSON
【发布时间】:2021-10-29 05:11:22
【问题描述】:

Python 脚本

import requests
import json
from bs4 import BeautifulSoup
import re

url = 'https://www.dunelm.com/product/caldonia-check-natural-eyelet-curtains-1000187301?defaultSkuId=30729125'

r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')

# Save source code to file for testing
with open("sourcecode.html", "w", encoding='utf-8') as file:
    file.write(str(soup))

# Regex pattern to capture JSON data within webpage source code
regex_pattern = r"{\"delivery\"*.*false*}}}"

网址https://www.dunelm.com/product/caldonia-check-natural-eyelet-curtains-1000187301?defaultSkuId=30729125

我正在尝试使用 Regex 提取嵌入在上述 URL 的 源代码 中的 JSON 数据。

我已手动从列出的 URL 中提取源代码,并使用以下 regex 模式输入regex101.com

{\"delivery\"*.*false*}}}

正则表达式模式似乎可以捕获所需的 JSON 数据。

问题

当我查看 soup 变量 的内容或保存的文件时,它似乎捕获了 HTML 源代码。
但是,我不知道如何处理正则表达式以仅捕获构建所需的 Python 字典所需的 JSON 数据字符串。

任何帮助将不胜感激。

【问题讨论】:

  • 你试过这个吗:对于soup.find_all(re.compile("__your_re_patter"))中的内容:print(content)

标签: python html json regex parsing


【解决方案1】:

也许这样的事情可以帮助你:

url = 'https://www.dunelm.com/product/caldonia-check-natural-eyelet-curtains-1000187301?defaultSkuId=30729125'

r = requests.get(url)
source_text = r.text
# Regex for extract info
json = re.findall('put your regex here', source_text)

要将返回的列表转换为 json,您可以使用:

import json
json_format = json.dumps(json)

【讨论】:

  • Excellent ... 以上从源代码中提取了 JSON 部分作为 LIST 类型。如何将列表转换为字典。过去我会使用 data = json.loads(json) 之类的东西,但他会抛出错误。
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 2010-11-14
  • 1970-01-01
  • 2010-12-21
  • 2018-02-03
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多