【发布时间】: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*}}}"
我正在尝试使用 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