Python3.5爬取cbooo.cn数据并且同步到mysql中
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# Python: 3.5
# Author: wucl(),zhenghai.zhang
# Program: 爬取CBO网站上所有电影的名称并写入数据库。
# Version: 0.1
# History: 2017.10.25 import requests,time, pymysql, re, datetime
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody host = 'xxx'
user = 'xxx'
passwd = 'xxx'
dbme = 'crawl'
dbtarget = 'back_brace'
table = 'movie_hotwords'
tabledelta = 'movie_hotwords_delta'
tablesync = 'slot_value'
port = 3306
tolist = ['xxx@xxx.com'] def get_info():
try:
url = 'http://www.cbooo.cn/Mdata/getMdata_movie?area=50&type=0&year=0&initial=%E5%85%A8%E9%83%A8&pIndex=1'
pData = requests.get(url).json()
return pData['tPage'], pData['tCount']
except:
print("获取总页数和总电影数失败") def get_movies(page):
try:
url = 'http://www.cbooo.cn/Mdata/getMdata_movie?area=50&type=0&year=0&initial=%E5%85%A8%E9%83%A8&pIndex=' + str(page)
pData = requests.get(url).json()
movies_list = pData['pData']
return movies_list
except:
print('获取第%s页电影列表失败' % page) def Movie_insert(host, user, passwd, dbme, port, table, movies_list):
conn=pymysql.connect(host=host, user=user, passwd=passwd, db=dbme, port=port, charset="utf8")
cur=conn.cursor()
new_movies = []
punc = "!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏.()::。·"
punctuation = punc
for movie in movies_list:
try:
movie['MovieName'] = re.sub(r"[%s]+" % punctuation, "", movie["MovieName"])
cmd = 'insert into %s(movie_id, movie_name) values("%s", "%s")' % (table, movie['ID'], movie['MovieName'])
cur.execute(cmd)
new_movies.append(movie)
except pymysql.Error:
print(" "*20, movie['MovieName'], "already exists, skip……")
cur.close()
conn.commit()
conn.close()
return new_movies def Movie_new_and_sync(host, user, passwd, dbme, dbtarget, port, tabledelta, movies_list, tablesync):
conn = pymysql.connect(host=host, user=user, passwd=passwd, db=dbme, port=port, charset="utf8")
cur = conn.cursor()
cur.execute("delete from %s " % dbme+"."+tabledelta) for movie in movies_list:
try:
cmd = 'insert into %s(movie_id, movie_name) values("%s", "%s")' % (tabledelta, movie['ID'], movie['MovieName'])
cmdsync = 'insert into %s(slot_type_id, slot_value, create_by, modify_by, gmt_create, gmt_modify, out_value) values("%s", "%s", "%s", "%s", "%s", "%s", "%s")' % (dbtarget+"."+tablesync, "xxxxxx", movie['MovieName'], "system", "system", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),"")
cur.execute(cmd)
cur.execute(cmdsync)
except pymysql.Error:
print(" " * 20, movie['MovieName'], "already exists, skip……") try:
cmdbacktoskill = 'insert into back_brace.release_task(app_type,app_status,type,ref_id,status,register_id,create_by,modify_by,gmt_create,gmt_modify) values("BACKBRACE","testpass","SLOT","xxxxxx","init","SLOT_BACKBRACE_TESTPASS" ,"zhenghai.zhang","zhenghai.zhang","%s","%s")' % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
cmdskilltoskillpro = 'insert into back_brace.release_task(app_type,app_status,type,ref_id,status,register_id,create_by,modify_by,gmt_create,gmt_modify) values("SKILL","deploy","SLOT","xxxxxx","init","SLOT_SKILL_DEPLOY" ,"zhenghai.zhang","zhenghai.zhang","%s","%s")' % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) print(cmdbacktoskill)
cur.execute(cmdbacktoskill)
print(cmdskilltoskillpro)
cur.execute(cmdskilltoskillpro)
except pymysql.Error:
print("write into back_brace.release_task error!!!")
cur.close()
conn.commit()
conn.close() def Email(to, subject, body):
creds = Credentials(
username='xxxxxx',
password='xxxxxx')
account = Account(
primary_smtp_address='xxx@xxx.com',
credentials=creds,
autodiscover=True,
access_type=DELEGATE)
m = Message(
account=account,
subject=subject,
body=HTMLBody(body),
to_recipients=[Mailbox(email_address=to)])
m.send_and_save() if __name__ == '__main__':
update_movies = []
pages, counts = get_info()
pages = 1
for i in range(1,pages + 1):
print("*"*30,i,"*"*30)
movies_list = get_movies(i)
new_movies = Movie_insert(host, user, passwd, dbme, port, table, movies_list)
for new_movie in new_movies:
print(new_movie['MovieName'],"Added")
onemovie = {}
onemovie["ID"] = new_movie["ID"]
onemovie["MovieName"] = new_movie["MovieName"]
update_movies.append(onemovie)
time.sleep(1)
print(update_movies) try:
Movie_new_and_sync(host, user, passwd, dbme, dbtarget, port, tabledelta, update_movies, tablesync) # 将增加的电影写入movie_hotwords_delta表中
except:
print("Movie update and sync Error!") subject = '本次新增电影名称'
body = "本次新增的电影名称为:<hr>"
for movie in update_movies:
body += movie["MovieName"] + "<br>"
for to in tolist:
Email(to, subject, body)
欢迎大侠指点
Python3.5爬取cbooo.cn数据并且同步到mysql中的更多相关文章
- Python3.5爬取豆瓣电视剧数据并且同步到mysql中
#!/usr/local/bin/python # -*- coding: utf-8 -*- # Python: 3.5 # Author: zhenghai.zhang@xxx.com # Pro ...
- node 爬虫 --- 将爬取到的数据,保存到 mysql 数据库中
步骤一:安装必要模块 (1)cheerio模块 ,一个类似jQuery的选择器模块,分析HTML利器. (2)request模块,让http请求变的更加简单 (3)mysql模块,node连接mysq ...
- Python爬取新浪微博评论数据,写入csv文件中
因为新浪微博网页版爬虫比较困难,故采取用手机网页端爬取的方式 操作步骤如下: 1. 网页版登陆新浪微博 2.打开m.weibo.cn 3.查找自己感兴趣的话题,获取对应的数据接口链接 4.获取cook ...
- 一个简易的Python爬虫,将爬取到的数据写入txt文档中
代码如下: import requests import re import os #url url = "http://wiki.akbfun48.com/index.php?title= ...
- Python3从零开始爬取今日头条的新闻【三、滚动到底自动加载】
Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...
- Python3:爬取新浪、网易、今日头条、UC四大网站新闻标题及内容
Python3:爬取新浪.网易.今日头条.UC四大网站新闻标题及内容 以爬取相应网站的社会新闻内容为例: 一.新浪: 新浪网的新闻比较好爬取,我是用BeautifulSoup直接解析的,它并没有使用J ...
- 吴裕雄--天生自然python数据清洗与数据可视化:MYSQL、MongoDB数据库连接与查询、爬取天猫连衣裙数据保存到MongoDB
本博文使用的数据库是MySQL和MongoDB数据库.安装MySQL可以参照我的这篇博文:https://www.cnblogs.com/tszr/p/12112777.html 其中操作Mysql使 ...
- Python爬取招聘网站数据,给学习、求职一点参考
1.项目背景 随着科技的飞速发展,数据呈现爆发式的增长,任何人都摆脱不了与数据打交道,社会对于“数据”方面的人才需求也在不断增大.因此了解当下企业究竟需要招聘什么样的人才?需要什么样的技能?不管是对于 ...
- Java爬取同花顺股票数据(附源码)
最近有小伙伴问我能不能抓取同花顺的数据,最近股票行情还不错,想把数据抓下来自己分析分析.我大A股,大家都知道的,一个概念火了,相应的股票就都大涨. 如果能及时获取股票涨跌信息,那就能在刚开始火起来的时 ...
随机推荐
- 开发 Swift 和 Objective-C 混编的 Framework
来源:黄文臣 blog.csdn.net/hello_hwc/article/details/58320433 前言 为什么要写这样一篇文章,因为昨天和一个朋友讨论到Swift和Objective C ...
- Ubuntu菜鸟入门(十六)—— 安装视频播放器vlc
sudo add-apt-repository ppa:videolan/master-daily sudo apt-get update sudo apt-get install vlc Ubunt ...
- HDU 4585 Shaolin (STL)
Shaolin Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Sub ...
- Event事件的兼容性(转)
window.event问题问题说明:window.event 只能在IE下运行,而不能在Firefox下运行,这是因为Firefox的event只能在事件发生的现场使用.解决方法:在事件发生的函数上 ...
- C# 因IIS回收导致定时器失效的解决方案
首先不要设置iis自动回收,一般设置凌晨1-2点左右回收一次,当凌晨iis回收应用程序池的时候,会调用Application_End,执行里面的代码, 重新启动网站,建议定时器的代码放在Session ...
- Runway for Mac(UML 流程图绘图工具)破解版安装
1.软件简介 Runway 是 macOS 系统上一款强大实用的软件开发工具,Runway for Mac 是一个界面简单功能强大的UML设计师.此外,Runway for Mac 带给你所有你 ...
- spring-data-redis读写分离
在对Redis进行性能优化时,一直想对Redis进行读写分离.但由于项目底层采用spring-data-redis对redis进行操作,参考spring官网却发现spring-data-redis目前 ...
- spring cloud 之 Feign 使用HTTP请求远程服务
一.Feign 简介 在spring Cloud Netflix栈中,各个微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端.我们可以使用JDK原生的URLCo ...
- linux记录sftp命令
使用以下配置方法不需要配置chroot. 编辑sshd_config文件 vi /etc/ssh/sshd_config 增加: Subsystem sftp /usr/libexec/openssh ...
- OLTP和OLAP有何区别?
OLTP即联机事务处理,就是我们经常说的关系数据库,意即记录即时的增.删.改.查,就是我们经常应用的东西,这是数据库的基础:OLAP即联机分析处理,是数据仓库的核心部心,所谓数据仓库是对于大量已经由O ...