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

文章目录

  • [1. 分析页面内容数据格式](#1. 分析页面内容数据格式)
  • [2. 使用re.findall方法,爬取新闻](#2. 使用re.findall方法,爬取新闻)
  • [3. 使用re.search 方法,爬取新闻](#3. 使用re.search 方法,爬取新闻)

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

  • 打开 https://36kr.com/

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

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

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

  • 在Name 列,找到 36kr.com 条目,右侧自动显示网页的相关内容:Headers, Preview, Response ... ...

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

2. 使用re.findall方法,爬取新闻

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

复制代码
import re
import requests
import json


# URL路径
url = "https://36kr.com/"
response = requests.get(url)
str1 = response.content.decode()

# 查找,使用正在表达式->取数组的第一个
result = re.findall("<script>window.initialState=(.*?)</script>", str1)[0]

# 先写入到本地,再查看
with open("36kr.json", "w", encoding="utf-8") as f:
    f.write(result)
    
# 加载json转换成python类型
json_result = json.loads(result)
print(json_result)


# pretty print the data: 其中 json.dumps() 对数据格式进行了美化:
print(json.dumps(json_result, indent=4))

print(f'data.theme        = {json_result["theme"]}')
print(f'data.isSpider     = {json_result["isSpider"]}')

for item in json_result["channel"]:
    print(f'name = {item["name"]}, '
          f'key = {item["key"]} ')

运行结果:


3. 使用re.search 方法,爬取新闻

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

复制代码
import re
import json
import requests


# URL路径
url = "https://36kr.com/"
html_doc = requests.get(url).text


data = re.search(r"<script>window.initialState=(.*?)</script>", html_doc)
print(f"data = {data}")

json_result = json.loads(data.group(1))
print(f"json_data = {json_result}")

# pretty print the data:
print(f"json_dump = {json.dumps(json_result, indent=4)}")

print(f'data.theme        = {json_result["theme"]}')
print(f'data.isSpider     = {json_result["isSpider"]}')

for item in json_result["channel"]:
    print(f'name = {item["name"]}, '
          f'key = {item["key"]} ')

运行结果:


相关推荐
玄同7651 小时前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
小瑞瑞acd1 小时前
【小瑞瑞精讲】卷积神经网络(CNN):从入门到精通,计算机如何“看”懂世界?
人工智能·python·深度学习·神经网络·机器学习
火车叼位2 小时前
也许你不需要创建.venv, 此规范使python脚本自备依赖
python
火车叼位2 小时前
脚本伪装:让 Python 与 Node.js 像原生 Shell 命令一样运行
运维·javascript·python
孤狼warrior2 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Katecat996632 小时前
YOLO11分割算法实现甲状腺超声病灶自动检测与定位_DWR方法应用
python
玩大数据的龙威2 小时前
农经权二轮延包—各种地块示意图
python·arcgis
ZH15455891312 小时前
Flutter for OpenHarmony Python学习助手实战:数据库操作与管理的实现
python·学习·flutter
belldeep3 小时前
python:用 Flask 3 , mistune 2 和 mermaid.min.js 10.9 来实现 Markdown 中 mermaid 图表的渲染
javascript·python·flask
喵手3 小时前
Python爬虫实战:电商价格监控系统 - 从定时任务到历史趋势分析的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·电商价格监控系统·从定时任务到历史趋势分析·采集结果sqlite存储