爬虫网页内容生成html

本文详细介绍了如何通过Python进行数据抓取,包括明确需求、使用浏览器开发者工具抓包、模拟请求、获取网络源代码、解析HTML内容(使用正则表达式、CSS选择器和XPath)、以及将数据保存为HTML或PDF文件的过程。
摘要由CSDN通过智能技术生成

一、数据来源分析

1.明确需求

明确网站url

数据内容 ->html

2.抓包分析

打开浏览器开发者工具,(右击检查),刷新

通过关键字搜索

在标头中找到网址,cookie

二、代码实现

1、发送请求

模拟浏览器发送请求->url:唯一资源定位符

模拟浏览器:headers = {user-agent:}

请求标头里的内容

构建键值对

请求网址:url =

发送请求:get/post(在请求方法中显示)

post请求参数:在载荷中

get请求参数:直接在网址中 spm=。。。。。

re

2.获取数据

即网络源代码(返回相应数据)

获取相应数据三种方式:

  • response.text

获取响应文本数据(字符串)网页源代码

  • response.json()

json数据(字典/列表)

  • response.content
  • 获取二进制数据(图片/音频)

 

3.解析数据

提取文章(标题、内容)

解析方法

re正则表达式:字符串数据

css选择器:根据标签属性

xpath节点提取:标签节点

css选择器方法
id=''ID名 (有id就先用id

class=''

标签名h1

#定位id名:#id title=selector.css('#articleContentId::text').get()

#class:.类名

4.保存数据

保存本地

文章内容--》html--》pdf

sponse=requests.get(url=url,headers=headers)

import requests
import  parsel
import pdfkit



'''发送请求'''
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0'
           }
url = 'https://blog.csdn.net/weixin_48201324/article/details/121484930'

response = requests.get (url = url ,headers = headers)
html = response.text
#把html字符串数据转成可解析对象
selector = parsel.Selector(html)
#css xpath方法
#定位id名:#id
#class:.类名
title =selector.css('#articleContentId::text').get()
#<h1 class="title-article" id="articleContentId">
print (title)
content = selector.css('#content_views').get()#获取正文全部标签,保存html模式
print(content)
#保存数据
#前端模版
html_str = '''
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <title>Document</title>
</head>
<body>
   {article}
</body>
</html>
'''
#字符串格式化方法
html_data = html_str.format(article=content)
print (html_data)
# 截取前10个字符作为文件名
title = title[:10]
new_title = title[:10]
#文件路径
html_path = 'html\\'+new_title+'.html'
with open(html_path,mode = 'w',encoding='utf-8') as f:
    f.write(html_data)

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值