介绍:
主要采集CSDN的文章,也是以学习为主。
环境使用:
- Python 3.8
Pycharm
- 翻译插件 translation
模块使用:
- requests >>> pip install requests
- from fake_useragent import UserAgent -- UA的库
- from lxml import etree -- XPath解析用的
- import time
- import os
- import re
如果安装python第三方模块:
- win + R 输入 cmd 点击确定, 输入安装命令 pip install 模块名 (pip install requests) 回车
- 在pycharm中点击Terminal(终端) 输入安装命令
如何配置pycharm里面的python解释器?
- 选择file(文件) >>> setting(设置) >>> Project(项目) >>> python interpreter(python解释器)
- 点击齿轮, 选择add
- 添加python安装路径
建议安装虚拟环境的第三方库 virtualenv 来管理虚拟环境
实现流程思路:
- 对要采集的页面发送请求 分析得到的响应 -> F12 <查看请求头的信息>
- 获取数据, 获取response响应数据
- 解析数据, 提取我们想要数据内容 —> 通过re定位需要的数据
- 保存数据, 到指定创建好的文件夹
- 多页采集, for循环轻松搞定
代码:
# -*- coding:utf-8 -*-
# @Author:🎈RedBalloon
# @Time:2022/10/4-14:56
# @File:csdnSpider.py
import requests
from fake_useragent import UserAgent
from lxml import etree
import time
import os
import re
# 获取页面的html信息
def get_page(page_url):
headers = {
'user-agent': UserAgent().random,
}
try:
response = requests.get(url=page_url, headers=headers)
response.raise_for_status()
if response.status_code == 200:
return response
except:
print('不对!有问题')
def parse(html_data):
tree = etree.HTML(html_data)
lis = tree.xpath('//*[@id="column"]/ul/li')
for li in lis:
links = li.xpath('./a/@href')[0]
# './a/div[1]/h2 || //*[@id="column"]/ul/li/a/div[1]/h2'
titles = li.xpath('./a/div[1]/h2/text()')[0].strip()
# print(titles, links) # 测试
# 如果后续保存文件时文件名出现windows不允许的字符时可以这样做,出现这些字符文件会保存不了
titles = re.sub(r'[/\*"<>|:]', '', titles)
time.sleep(1)
response_info_page = get_page(links)
info_html = response_info_page.text
content_html = re.findall(r'<link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-6e43165c0a.css">(.*?)<link href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/markdown_views-22a2fefd3b.css" rel="stylesheet">', info_html, re.S)[0]
# 替换掉空格,方便后续自动化上传到网站(这样不会样式混乱)
content_html = content_html.replace(' ', '')
save(titles, content_html)
def save(title_info, content_html_data):
import html # 一个html的<!DOCTYPE html>生成骨架,自己修改,通过format方法传入获取的html数据
html_data = html.html_header.format(title=title_info, article=content_html_data)
# 文件保存路径
folder_name = 'Python零基础入门篇'
html_data_path = f'{folder_name}\\'
if not os.path.exists(html_data_path):
os.mkdir(html_data_path)
with open(html_data_path + title_info + '.html', mode='w', encoding='utf-8')as f:
f.write(html_data)
print(f'正在保存======{title_info}')
def main():
url = 'https://blog.csdn.net/oh_python/category_11620063.html'
# 第二页数据,需要可以做个循环
# 'https://blog.csdn.net/oh_python/category_11620063_1.html'
# 'https://blog.csdn.net/oh_python/category_11620063_2.html'
html = get_page(url)
parse(html.text)
if __name__ == '__main__':
main()
评论 (0)