Python 爬取网页中的 JSON 数据:正则表达式和 BeautifulSoup 方法
要爬取网页中 script 标签中的 JSON 数据,可以使用 Python 中的正则表达式或者第三方库如 BeautifulSoup 来提取数据。
以下是使用正则表达式的示例代码:
import re
import requests
# 发送请求获取网页内容
url = 'https://example.com'
response = requests.get(url)
html = response.text
# 使用正则表达式提取 script 标签中的 json 数据
pattern = r'<script.*?>(.*?)</script>'
scripts = re.findall(pattern, html, re.S)
# 遍历所有的 script 标签
for script in scripts:
# 判断是否包含 json 数据
if 'var data' in script:
# 提取 json 数据
pattern = r'var data = (.*?);'
json_data = re.findall(pattern, script)[0]
print(json_data)
在上述代码中,首先使用 requests 库发送请求获取网页内容,然后使用正则表达式提取 script 标签中的内容。接着,使用正则表达式提取 json 数据,并打印出来。
如果你更喜欢使用 BeautifulSoup 库,以下是使用 BeautifulSoup 的示例代码:
import requests
from bs4 import BeautifulSoup
# 发送请求获取网页内容
url = 'https://example.com'
response = requests.get(url)
html = response.text
# 使用 BeautifulSoup 解析网页内容
soup = BeautifulSoup(html, 'html.parser')
# 遍历所有的 script 标签
for script in soup.find_all('script'):
# 判断是否包含 json 数据
if 'var data' in script.string:
# 提取 json 数据
json_data = script.string.split('var data = ')[1].strip(';')
print(json_data)
在上述代码中,首先使用 requests 库发送请求获取网页内容,然后使用 BeautifulSoup 解析网页内容。接着,遍历所有的 script 标签,判断是否包含 json 数据,并提取出来。最后,打印出 json 数据。
原文地址: http://www.cveoy.top/t/topic/fbLx 著作权归作者所有。请勿转载和采集!