python爬虫 - 爬取html中的script数据(zum.com新闻信息 )

文章目录

  • [1. 分析页面内容数据格式](#1. 分析页面内容数据格式)
  • [2. 使用re.findall方法,编写爬虫代码](#2. 使用re.findall方法,编写爬虫代码)
  • [3. 使用re.search 方法,编写爬虫代码](#3. 使用re.search 方法,编写爬虫代码)

1. 分析页面内容数据格式

(1)打开 https://zum.com/

(2)按F12(或 在网页上右键 --> 检查(Inspect))

(3)找到网页上的Network(网络)部分

(4)鼠标点击网页页面,按 Ctrl + R 刷新网页页面,可以看到 NetWork(网络)部分会刷新出很多的网络信息

(5)在Name 列,找到 zum.com 条目,右侧自动显示网页的相关内容:Headers, Preview, Response ... ...

(6)分析Response内容,所需要关心的内容,位于整个html页面的下面


2. 使用re.findall方法,编写爬虫代码

要点:从window.INITIAL_STATE=到;之间的数据都是json数据。 json.loads会自动将false转为False, true转为True

复制代码
import re
import requests
import json


url = "https://zum.com/"
response = requests.get(url)
str1 = response.content.decode()

result = re.findall(r"window\.__INITIAL_STATE__=(.*?}});", str1)  

json_result = json.loads(result[0])
print(f"json_result = [{json_result}]")

print(f'data.fetchedCommonResponse  = {json_result["fetchedCommonResponse"]}')
print(f'data.isDarkTheme                       = {json_result["isDarkTheme"]}')

for item in json_result["headerStore"]["gnb"]["gnbItems"]:
    print(f'idx = {item["idx"]}, '
          f'title = {item["title"]} ')

运行结果:

使用工具格式化后数据内容:

3. 使用re.search 方法,编写爬虫代码

要点:从window.INITIAL_STATE=到;之间的数据都是json数据。 json.loads会自动将false转为False, true转为True

复制代码
import re
import json
import requests

url = "https://zum.com/"
html_doc = requests.get(url).text

data = re.search(r"window\.__INITIAL_STATE__=(.*?}});", html_doc)
print(f"data = {data}")

data = json.loads(data.group(1))
print(data)

# pretty print the data:
print(json.dumps(data, indent=4))

print(f'data.fetchedCommonResponse        = {data["fetchedCommonResponse"]}')
print(f'data.isDarkTheme                  = {data["isDarkTheme"]}')

for item in data["headerStore"]["gnb"]["gnbItems"]:
    print(f'idx = {item["idx"]}, '
          f'title = {item["title"]} ')

运行结果如下,其中 json.dumps() 对数据格式进行了美化:


相关推荐
熊猫钓鱼>_>几秒前
2025反爬虫之战札记:从robots.txt到多层防御的攻防进化史
开发语言·c++·爬虫
励志不掉头发的内向程序员37 分钟前
从零开始的python学习——文件
开发语言·python·学习
THMAIL1 小时前
量化基金从小白到大师 - 金融数据获取大全:从免费API到Tick级数据实战指南
人工智能·python·深度学习·算法·机器学习·金融·kafka
代码欢乐豆1 小时前
scikit-learn零基础配置(含python、anaconda)
python·机器学习·scikit-learn
Java水解2 小时前
Python数据库操作:SQLAlchemy ORM指南
python
悠哉悠哉愿意2 小时前
【数学建模学习笔记】无监督聚类模型:分层聚类
笔记·python·学习·数学建模
eleqi2 小时前
Python+DRVT 从外部调用 Revit:批量创建门
python·系统集成·bim·revit·drvt·自动生产流水线
先做个垃圾出来………2 小时前
PyTorch 模型文件介绍
人工智能·pytorch·python
浅醉樱花雨2 小时前
vosk语音识别实战
人工智能·python·语音识别·asr·vosk
再努力"亿"点点2 小时前
爬取m3u8视频完整教程
开发语言·python