python爬虫之爬取网站到数据库
一、根据已有程序运行得到的结果

完整代码如下:
import sqlite3; class DB(object):
"""数据库访问方法的实现"""
"""初始化api 产生数据操作的对象 conect 操作的游标"""
def __init__(self):
self.conn={};
self.cus={};
#初始化数据库链接的api
#1产生数据库链接对象
self.conn=sqlite3.connect(r'Test.db');
#2.产生操作的游标
self.cus=self.conn.cursor();
pass;
def create_table(self): sql = " CREATE TABLE if not exists mynews (CrawlTime char,Title char,Content char,PublishTime char,Origin char)"
self.conn.execute(sql)
self.conn.commit()
print('create table successfully')
def insert_into_news(self,ops):
self.conn.execute('insert into mynews(CrawlTime,Title,Content,PublishTime,Origin) values(?,?,?,?,?)',(ops['CrawlTime'],ops['Title'],ops['Content'],ops['PublishTime'],ops['Origin'],));
self.conn.commit();
pass

完整代码如下:
#要求使用urllib3
import urllib.request;
from bs4 import BeautifulSoup;
from DB.DB import DB; db=DB();
import time;
"""爬取核心的核心模块,功能只负责爬取研究生调剂信息""" class DrawStu():
"""docstring for DrawStu"""
def __init__(self):
self.baseurl='https://yz.chsi.com.cn/kyzx/tjxx/';
db.create_table();
pass; #提取公共的爬取信息的api
def commonsdk(self,url):
response=urllib.request.urlopen(url);#注意 写在内部以后 变成了形参
html=response.read();#read进行乱码处理
print(html);
doc=BeautifulSoup(html);
return doc; #爬取基本列表
def draw_base_list(self,url):
print('url is:::',url);
doc=self.commonsdk(url);
lilist=doc.find('ul',{'class':'news-list'}).findAll('li');
#print(lilist);
#爬取一级参数
for x in lilist:
Title=x.find('a').text;
Time=x.find('span').text
Link='https://yz.chsi.com.cn'+x.find('a').get('href');
#print(Link);
self.draw_detail_list(Link,Title,Time);
pass pass #爬取二级详情的信息参数
def draw_detail_list(self,url,Title,Time):
doc=self.commonsdk(url);
from_info=doc.find('span',{'class':'news-from'}).text; content=doc.find('div',{'class':'content-l detail'}).text; ctime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()); #将数据 拼合成字典 交给数据库存储的api
data={
'CrawlTime':ctime,
'Title':Title,
'Content':content,
'PublishTime':Time,
'Origin':from_info
}
print(data);
print('插入数据库中'); db.insert_into_news(data);
pass #爬取页面的总页数
def get_page_size(self):
requesturl=self.baseurl;
pcxt=self.commonsdk(requesturl).find('div',{'class':'pageC'}).findAll('span')[0].text;
print(pcxt);
#re正则表达式 字符串截取api
pagesize=pcxt.strip();
pagearr=pagesize.split('/');
pagestr=pagearr[1];
return int(pagestr[0:2]);
pass

完整代码如下:
from DrawStu.DrawStu import DrawStu;
import time;
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')
#初始化class 得到对象
draw=DrawStu();
if __name__ == '__main__':
print('爬取研究生调剂信息');
size=draw.get_page_size();
print(size)
for x in range(size):
start=x*50;
print(start);
#print();
created_url='https://yz.chsi.com.cn/kyzx/tjxx/?start='+str(start);
draw.draw_base_list(created_url); pass
数据库界面截图:

二、对于已有代码的理解
部分代码注释:
改变标准输出的默认编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
改变标准输出的默认编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030')
程序运行后乱码:

防止其乱码的代码:

在网上搜索找到的解决方法:

例子代码如下:
"""
@Author : 行初心
@Date : 18-9-24
@Blog : www.cnblogs.com/xingchuxin
@Gitee : gitee.com/zhichengjiu
"""
import urllib.request def main(): url = "" # 服务器给的响应
response = urllib.request.urlopen(url) # 返回一个二进制字符串: b'',无法正常阅读
html = response.read() # 进行解码操作
code_of_html = html.decode('utf-8') # 打印查看网页源代码
print(code_of_html) if __name__ == '__main__':
main()
修改代码,加上一行解码的的代码后再输出,修改后代码如下:

修改后运行结果无乱码:

python爬虫之爬取网站到数据库的更多相关文章
- python爬虫:爬取网站视频
python爬取百思不得姐网站视频:http://www.budejie.com/video/ 新建一个py文件,代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 ...
- Python爬虫之爬取慕课网课程评分
BS是什么? BeautifulSoup是一个基于标签的文本解析工具.可以根据标签提取想要的内容,很适合处理html和xml这类语言文本.如果你希望了解更多关于BS的介绍和用法,请看Beautiful ...
- [Python爬虫] Selenium爬取新浪微博客户端用户信息、热点话题及评论 (上)
转载自:http://blog.csdn.net/eastmount/article/details/51231852 一. 文章介绍 源码下载地址:http://download.csdn.net/ ...
- Python爬虫之爬取站内所有图片
title date tags layut Python爬虫之爬取站内所有图片 2018-10-07 Python post 目标是 http://www.5442.com/meinv/ 如需在非li ...
- python爬虫实战---爬取大众点评评论
python爬虫实战—爬取大众点评评论(加密字体) 1.首先打开一个店铺找到评论 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经 ...
- from appium import webdriver 使用python爬虫,批量爬取抖音app视频(requests+Fiddler+appium)
使用python爬虫,批量爬取抖音app视频(requests+Fiddler+appium) - 北平吴彦祖 - 博客园 https://www.cnblogs.com/stevenshushu/p ...
- Python爬虫之爬取淘女郎照片示例详解
这篇文章主要介绍了Python爬虫之爬取淘女郎照片示例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 本篇目标 抓取淘宝MM ...
- 初次尝试python爬虫,爬取小说网站的小说。
本次是小阿鹏,第一次通过python爬虫去爬一个小说网站的小说. 下面直接上菜. 1.首先我需要导入相应的包,这里我采用了第三方模块的架包,requests.requests是python实现的简单易 ...
- python爬虫项目-爬取雪球网金融数据(关注、持续更新)
(一)python金融数据爬虫项目 爬取目标:雪球网(起始url:https://xueqiu.com/hq#exchange=CN&firstName=1&secondName=1_ ...
随机推荐
- springboot~maven集成开发里的docker构建
统一设计 maven很好的把项目整合在一起,在部署时,每个项目可以有自己的Dockerfile,在构建后把对应的jar包复制到Dockerfile的同级目录,使用使用统一的打包镜像和容器启动方法去执行 ...
- Change Style of Navigation Items 更改导航项的样式
In this lesson, you will learn how to change the style of navigation items in a WinForms XAF applica ...
- [springMvc]常见配置
[springMvc]常见配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=&qu ...
- MinU: v2 Vulnhub Walkthrough
主机层面扫描: 22 和 3306 端口 3306 端口默认是MySQL端口,但是这里尝试爆破报错,最后通http访问发现非MySQL协议,而是一个http的服务 http的协议我们进行目录枚举下 枚 ...
- English:Root "tele"
Xx_Introduction tele mean "far" mean"faar" cognate word have tele\culture\tel\pa ...
- iOS----------jenkins
错误日志: ERROR: Error fetching remote repo 'origin' Finished: FAILURE ERROR: Error cloning remote repo ...
- 原创【cocos2d-x】CCMenuItemToggle 在lua中的使用
说明:1,所使用的cocos2dx版本为2.1.3 ;09:48:05 2,本人仍是在学习中的小菜鸟,此博客只是为了记录我学习过程中的点滴,同时也希望同样lua开发的童鞋,一起交流: 3,本人whj0 ...
- Java程序远程无法执行nohup命令
问题的上下文: 由于生产无法使用 jenkins 发布,所以采用 ch.ethz.ssh2 或叫 ganymed-ssh2 的开源 java 的 ssh api 进行远程发布. 在发起重启时,远程执行 ...
- python 读取ini 配置文件
安装 pip install configparser 1 配置文件 config.ini: [MysqlDB]user=rootpasswd=123456sport=3306db_name=my_d ...
- windows本地连不上虚拟机redis服务完美解决
检查本机与虚拟机是否可以互相ping通,如本机IP:192.168.22.111 虚拟机IP:192.168.44.129 (设置虚拟机静态IP已设置) 本机 win+R 输入cmd 进入dos 输 ...