#!/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中的更多相关文章

  1. Python3.5爬取豆瓣电视剧数据并且同步到mysql中

    #!/usr/local/bin/python # -*- coding: utf-8 -*- # Python: 3.5 # Author: zhenghai.zhang@xxx.com # Pro ...

  2. node 爬虫 --- 将爬取到的数据,保存到 mysql 数据库中

    步骤一:安装必要模块 (1)cheerio模块 ,一个类似jQuery的选择器模块,分析HTML利器. (2)request模块,让http请求变的更加简单 (3)mysql模块,node连接mysq ...

  3. Python爬取新浪微博评论数据,写入csv文件中

    因为新浪微博网页版爬虫比较困难,故采取用手机网页端爬取的方式 操作步骤如下: 1. 网页版登陆新浪微博 2.打开m.weibo.cn 3.查找自己感兴趣的话题,获取对应的数据接口链接 4.获取cook ...

  4. 一个简易的Python爬虫,将爬取到的数据写入txt文档中

    代码如下: import requests import re import os #url url = "http://wiki.akbfun48.com/index.php?title= ...

  5. Python3从零开始爬取今日头条的新闻【三、滚动到底自动加载】

    Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...

  6. Python3:爬取新浪、网易、今日头条、UC四大网站新闻标题及内容

    Python3:爬取新浪.网易.今日头条.UC四大网站新闻标题及内容 以爬取相应网站的社会新闻内容为例: 一.新浪: 新浪网的新闻比较好爬取,我是用BeautifulSoup直接解析的,它并没有使用J ...

  7. 吴裕雄--天生自然python数据清洗与数据可视化:MYSQL、MongoDB数据库连接与查询、爬取天猫连衣裙数据保存到MongoDB

    本博文使用的数据库是MySQL和MongoDB数据库.安装MySQL可以参照我的这篇博文:https://www.cnblogs.com/tszr/p/12112777.html 其中操作Mysql使 ...

  8. Python爬取招聘网站数据,给学习、求职一点参考

    1.项目背景 随着科技的飞速发展,数据呈现爆发式的增长,任何人都摆脱不了与数据打交道,社会对于“数据”方面的人才需求也在不断增大.因此了解当下企业究竟需要招聘什么样的人才?需要什么样的技能?不管是对于 ...

  9. Java爬取同花顺股票数据(附源码)

    最近有小伙伴问我能不能抓取同花顺的数据,最近股票行情还不错,想把数据抓下来自己分析分析.我大A股,大家都知道的,一个概念火了,相应的股票就都大涨. 如果能及时获取股票涨跌信息,那就能在刚开始火起来的时 ...

随机推荐

  1. Hibernate+maven+eclipse 实现自动建表

    一.需求 如题,当建好Model 时,不想自己手工建表,可以采取hibernate进行自动建表.下面将用一个小例子来说明如何将其实现. 二.实现 说明:1)这里用的是4.3.1.Final版本的hib ...

  2. iOS应用间相互跳转

    使用第三方用户登录,跳转到需授权的App.如QQ登录,微信登录等. 需要用户授权,还需要"返回到调用的程序,同时返回授权的用户名.密码". 应用程序推广,跳转到另一个应用程序(本机 ...

  3. 超酷的 Vim 搜索技巧

    尽管目前我们已经涉及 Vim 的多种特性,但此编辑器的特性集如此庞大,不管我们学习多少,似乎仍然远远不足.承接我们的 Vim 教程系列,本文我们将讨论 Vim 提供的多种搜索技术. 不过在此之前,请注 ...

  4. Ubuntu菜鸟入门(十四)—— 设置root密码

    sudo su - 输入你的账户的密码 passwd 输入新的root密码 再次输入新的root密码

  5. System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded

    昨天客户跟我说,突然一个页面频繁地报ThrowIfMaxHttpCollectionKeysExceeded这个异常.而且是数据量大的时候报错,数据量小的时候OK. 根据异常的名称也能看得差不多超过了 ...

  6. WinRAR破解

    新建记事本文件(txt文件),然后将文件另存为以 rarreg.key 为文件名的文件(当然由于设置的不同,可能出现你保存后的文件为 rarreg.key.txt 没关系,将其重命名,删掉.txt 会 ...

  7. MVC摘记

    2013年9月23日18:04:06 直接cshtml页面的js中使用     var customerId = @(ViewBag.Oppotunity as OppotunityDto==null ...

  8. dbms_random.seed

    语法: DBMS_RANDOM.SEED ( val IN BINARY_INTEGER); DBMS_RANDOM.SEED ( val IN VARCHAR2); val: Seed number ...

  9. Create PDB with Sample schemas in 12C

    查看: SQL> select * from ( 2 select username, account_status from dba_users order by created desc) ...

  10. matlab入门笔记(六):编程基础之M文件

    摘自<matlab从入门到精通>胡晓东 在Matlab中,用户可以在命令行中直接输入命令,从而以一种交互式的方式来编写程序.这种方式适用于命令行比较简单,输入比较方便,同时处理的问题较少的 ...