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


相关推荐
Thomas.Sir8 分钟前
重构诊疗效率与精准度之【AI 赋能临床诊断与辅助决策从理论到实战】
人工智能·python·ai·医疗·诊断
V胡桃夹子15 分钟前
pyenv-win 完整安装+使用手册
python·pyenv
ego.iblacat19 分钟前
Python 连接 MySQL 数据库
数据库·python·mysql
ZC跨境爬虫30 分钟前
【Scrapy实战避坑】5sing网站爬虫从0到1,踩遍动态渲染、正则匹配全坑(附完整解决方案)
爬虫·scrapy
humors2211 小时前
各厂商工具包网址
java·数据库·python·华为·sdk·苹果·工具包
pzx_0012 小时前
【优化器】 随机梯度下降 SGD 详解
人工智能·python·算法
大邳草民2 小时前
Python 中 global 与 nonlocal 的语义与机制
开发语言·笔记·python
程序员小远2 小时前
软件测试用例总结
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
2501_948114242 小时前
技术解码:Gemini交互式模拟API与高负载网关的选型逻辑
人工智能·python·ai
AC赳赳老秦2 小时前
OpenClaw text-translate技能:多语言批量翻译,解决跨境工作沟通难题
大数据·运维·数据库·人工智能·python·deepseek·openclaw