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"]} ')

运行结果:


相关推荐
千寻girling2 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook5 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风6 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风6 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习2 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员