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() 对数据格式进行了美化:


相关推荐
再玩一会儿看代码2 小时前
Ken的Java学习之路——Java中关于面向对象
java·开发语言·经验分享·python·学习
Q_Q5110082852 小时前
python+django/flask的美食交流宣传系统vue
spring boot·python·pycharm·django·flask·node.js·php
Q_Q5110082852 小时前
python+django/flask+vue的基层智能化人员调度系统pycharm-计算机毕业设计
spring boot·python·pycharm·django·flask·node.js
lapiii3584 小时前
[智能体设计模式] 第4章:反思(Reflection)
人工智能·python·设计模式
快乐非自愿5 小时前
Java垃圾收集器全解:从Serial到G1的进化之旅
java·开发语言·python
百锦再8 小时前
第11章 泛型、trait与生命周期
android·网络·人工智能·python·golang·rust·go
zbhbbedp282793cl10 小时前
如何在VSCode中安装Python扩展?
ide·vscode·python
Python私教12 小时前
Python 开发环境安装与配置全指南(2025版)
开发语言·python
Access开发易登软件12 小时前
Access导出带图表的 HTML 报表:技术实现详解
数据库·后端·html·vba·导出·access
百锦再12 小时前
第12章 测试编写
android·java·开发语言·python·rust·go·erlang