Python抓拍博客园文章,并存入数据库

  在学习python后,想做个爬虫,抓取博客园文章。

  爬虫思路很简单,模拟浏览器访问网页,得到网页的html代码,再根据页面结构,从html中提取自己需要的内容。

  本文代码主要分为3个部分:

  1、读取博客园首页文章链接。

    https://www.cnblogs.com/是博客园的首页,列出了文章,分析页面内容,读取文章的链接。

    这需要看页面的结构,可以使用浏览器,再浏览页面代码,选择元素,看界面上选中哪一部分,根据自己的需要,可以看到对应模块的代码。

  2、对于每个页面,分析页面内容。

    这需要看页面结构。

  3、分析完页面内容后,将需要的数据插入到数据库中。

数据设计:

 1 -- 博客系统爬虫模块
 2 -- 1、创建库
 3 drop database if exists blog_service_spider; -- 直接删除数据库,不提醒
 4 create database blog_service_spider; -- 创建数据库
 5 use blog_service_spider; -- 选择数据库
 6
 7 --
 8 -- table structure for table `spider_page`
 9 --
10 drop table if exists `spider_page`;
11
12 create table `spider_page` (
13   `id` varchar(60) not null comment ‘主键‘,
14   `create_time` datetime default current_timestamp comment ‘创建时间‘,
15   `creator` varchar(60) not null comment ‘创建人id‘,
16   `modified_time` datetime default null on update current_timestamp comment ‘修改时间‘,
17   `modifier` varchar(60) default null comment ‘修改人id‘,
18   `title` varchar(100) default null comment ‘文章标题‘,
19   `title_url` varchar(100) default null comment ‘文章地址‘,
20   `content` text default null comment ‘文章内容‘,
21   `post_time` datetime default null comment ‘文章发表时间‘,
22   `author` varchar(100) default null comment ‘作者‘,
23   `author_page` varchar(100) default null comment ‘作者主页‘,
24   primary key (`id`)
25 ) engine=innodb default charset=utf8 comment=‘抓取的文章‘;

python代码如下:

  1 ‘‘‘
  2 File Name:   webspider
  3 Author:      tim
  4 Date:        2018/7/27 14:36
  5 Description: 网页爬虫。抓取博客园首页文章,放入数据库中。
  6 放入数据库中的内容:标题、作者、发表时间、文章内容、文章地址、作者主页
  7 ‘‘‘
  8
  9 from urllib import request
 10 import ssl
 11 from bs4 import BeautifulSoup
 12 import pymysql
 13 import uuid
 14
 15
 16 # 传入url,读取url,将返回的页面转换成BeautifulSoup对象
 17 def html_parser(url):
 18     ssl._create_default_https_context = ssl._create_unverified_context  # 加入ssl
 19     req = request.Request(url)  # 构建请求
 20
 21     # 代理,模拟浏览器在访问,避免被屏蔽
 22     req.add_header(‘User-Agent‘,
 23                    ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36‘)
 24
 25     resp = request.urlopen(req)  # 发起请求
 26     html = resp.read().decode(‘utf-8‘)  # 转码
 27
 28     bf = BeautifulSoup(html, "html.parser")  # 将页面转换成BeautifulSoup对象
 29
 30     return bf
 31
 32
 33 # 分析单个网页
 34 def read_page(url):
 35     bf = html_parser(url)  # 获取BeautifulSoup对象
 36
 37     # 内容分析
 38     post_info = bf.find(‘div‘, class_=‘post‘)  # 有用的内容区域,下面的查找从该有用区域中进一步获取
 39
 40     title = post_info.find(id=‘cb_post_title_url‘).get_text()  # 文章标题
 41     title_url = post_info.find(id=‘cb_post_title_url‘)[‘href‘]  # 文章地址
 42     content = post_info.find(id=‘cnblogs_post_body‘)  # 文章内容
 43     postdate = post_info.find(id=‘post-date‘).get_text()  # 文章发表时间
 44     author = post_info.find(‘div‘, class_=‘postDesc‘).find(‘a‘).get_text()  # 作者
 45     author_page = post_info.find(‘div‘, class_=‘postDesc‘).find(‘a‘)[‘href‘]  # 作者主页
 46
 47     ‘‘‘print(title)
 48     print(title_url)
 49     print(content)
 50     print(postdate)
 51     print(author)
 52     print(author_page)‘‘‘
 53     # 分析完每个页面后,将页面内容插入到数据库中
 54     operate_db(title, title_url, content, postdate, author, author_page)
 55
 56
 57 # 分析博客园首页文章列表
 58 def read_post_list():
 59     bf = html_parser(‘https://www.cnblogs.com/‘)
 60     post_list = bf.find(id=‘post_list‘).find_all(‘div‘, class_="post_item")
 61     for post in post_list:
 62         page_url = post.find(‘div‘, class_=‘post_item_body‘).h3.a[‘href‘]
 63         # 读取每篇文章的url,分别进行页面分析
 64         read_page(page_url)
 65
 66
 67 # 操作数据库
 68 def operate_db(title, title_url, content, postdate, author, author_page):
 69     # 打开数据库连接
 70     conn = pymysql.connect(‘localhost‘, ‘root‘, ‘root‘, ‘blog_service_spider‘)
 71
 72     # 使用cursor()方法获取操作游标
 73     cursor = conn.cursor()
 74
 75     # 执行的sql
 76     insert_sql = "insert into spider_page (id,creator,title,title_url,content,post_time,author,author_page) values(%s,%s,%s,%s,%s,%s,%s,%s)"
 77
 78     # 生成的ID
 79     id = str(uuid.uuid1())
 80
 81     # 文章内容
 82     str_content = str(content)
 83
 84     # 创建人
 85     creator = ‘admin‘
 86
 87     try:
 88         cursor.execute(insert_sql,
 89                        (id, creator, title, title_url, str_content, postdate, author, author_page))  # 执行sql语句
 90         conn.commit()  # 提交到数据库执行
 91     except Exception as e:
 92         # 如果执行sql语句出现问题,则执行回滚操作
 93         conn.rollback()
 94         print(e)
 95     finally:
 96         # 不论try中的代码是否抛出异常,这里都会执行
 97         # 关闭游标和数据库连接
 98         cursor.close()
 99         conn.close()
100
101
102 # start
103 if __name__ == ‘__main__‘:
104     read_post_list()

原文地址:https://www.cnblogs.com/yangtze-yufei/p/9387742.html

时间: 2024-12-18 10:08:18

Python抓拍博客园文章,并存入数据库的相关文章

简单爬虫-抓取博客园文章列表

原文:简单爬虫-抓取博客园文章列表 如果使用对方网站数据,而又没有响应的接口,或者使用接口不够灵活的情况下,使用爬虫在合适不过了.爬虫有几种,对方网站展示形式有几种都是用分析,每个网站展示有相似的地方,有不同的地方. 大部分使用httpRequst就能完成,不管是否添加了口令.随即码.请求参数.提交方式get或者post.地址来源.多次响应等等.但是有些网站使用ajax如果是返回json或固定格式的也好处理,如果是很复杂的,可以使用webbrower控件进行抓取,最后正则解析,获取所需要的数据即

利用GitHook实现博客园文章的备份和自动发布

在使用vscode中的writecnblog插件时有所启发,链接: 用vscode写博客和发布,大家可以看看. 我们在本地可以利用git轻松实现博客园文章的历史记录管理,利用博客园的MetaWeblog API 别人的介绍编写小程序来自动化上传文章(参考插件). 更进一步,将这个程序放到githook里,每次commit时自动执行,就实现了现博客园文章的备份和自动发布. 这样,你每次发布文章的步骤就简化为: 编写本地一个Git仓库内的xx.md文件 commit更改 程序会自动获取diff,然后

利用GitHook实现博客园文章的备份和自动发布.md

在使用vscode中的writecnblog插件时有所启发,链接: [用vscode写博客和发布](https://www.cnblogs.com/caipeiyu/p/5475761.html),大家可以看看. 我们在本地可以利用git轻松实现博客园文章的历史记录管理,利用博客园的MetaWeblog API [别人的介绍](https://www.cnblogs.com/caipeiyu/p/5354341.html)编写小程序来自动化上传文章(参考插件). 更进一步,将这个程序放到gith

实用scrapy批量下载自己的博客园文章

首先,在items.py中定义几个字段用来保存网页数据(网址,标题,网页源码) 如下所示: import scrapy class MycnblogsItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() page_title = scrapy.Field() page_url = scrapy.Field() page_html = scrapy.Field() 最重要的是我

博客园文章添加版权信息的方法

管理--操作--博客签名,进入到制作签名的页面.在"内容"的文本框输入如下信息并替换相应的文字: <div>作者:<a href="http://www.cnblogs.com/lamp01/" target="_blank">郁冬</a></div><div>出处:<a href="http://www.cnblogs.com/lamp01/" target=

对博客园文章审核规则的质疑

几次发文章都被移出首页,让我很是郁闷. http://www.cnblogs.com/zhupengfei/p/8983666.html http://www.cnblogs.com/zhupengfei/p/8934072.html 移出的原因都是因为图片太多,文字太少. 我就很郁闷了,实例讲解,不用图片用什么?文字能有图片描述的清楚吗? 同样的文章在CSDN就没有任何问题,几分钟后就可以审核通过. 目前还有一个问题就是我在博客园发的文章无法被百度收录到,而在CSDN的却可以. 是否考虑转到C

JS批量删除博客园文章

$('tr').each(function(){ if($(this).attr('id')!=null){ var s = $(this).attr('id').slice(9); console.info("正在删除:"+s); deletePost(s); } }); window.location.reload(); 以前都是用新浪博客的,但是新浪博客对编程类文章支持不好,记录一些html代码总是隐藏. 第一次用博客园,被他简洁的界面吸引. 一看还有博客搬家功能,于是把新浪博客

python模拟博客园登录-基础版

mport timeimport inspectfrom functools import wrapsuser_status = {'username': None,'status': False} dic1 = { 1: '登录', 2: '注册', 3: '文章', 4: '日记', 5: '评论', 6: '收藏', 7: '注销', 8: '退出程序'} dic2 = { 3: 'artecle', 4: 'diary', 5: 'comment', 6: 'collection', 7

博客园文章转PDF之非多线程方式

问题: 现在博客园写的文章想要在自己本地存一份,一个一个复制有点麻烦,希望能够程序化解决这个问题 思路: 博客园园第二页会出现页码,可以通过请求第二页,获得页面信息,然后把总页码获取到 每个页面的地址一样除了页码的地方不一样,因此,循环总页码,就可以得到每一个文章列表页的内容 得到了文章列表页的内容,可以把每个文章列表的文章链接获取到,且放在list中 循环文章链接,访问文章页面,获取文章标题和内容,并加上head,得到文章HTML且排除了左边栏及上下底部 把生成的HTML且排除了非文章内容的文