python爬虫新浪新闻并存储数据到(mysql)数据库

 

1.准备工作

安装anconda科学计算环境(包含python),在安装一些所需要的库pip install (pymysql,jupyter)需要什么模块就安装哪个模块

2.代码以及解释 

#将网页读入 BeautifulSoup并用html.parser剖析器防止警告的产生
import requests
from bs4 import BeautifulSoup
res=requests.get('http://news.sina.com.cn/china/')
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')

 寻找新闻评论数的网址,如下图

python爬虫新浪新闻并存储数据到(mysql)数据库

#新闻评论数网址,其中{}内为每则新闻的标识
commenturl='http://comment5.news.sina.com.cn/page/info?version=1&\
format=json&channel=gn&newsid=comos-{}&group=undefined&\
compress=0&ie=utf-8&oe=utf-8&page=1&page_size=3&t_size=3&h_size=3'

动态获取新闻评论数的函数如下

#动态获取新闻的评论数
import re
import json
def getcomments(newsurl):
    m=re.search('doc-i(.*).shtml',newsurl)
    newsid=m.group(1)
    comments=requests.get(commenturl.format(newsid))
    jd = json.loads(comments.text.strip('var data='))
    return jd['result']['count']['total']

获取新闻的细节函数

#新闻的信息抽取函数
def getNewsDetail(newsurl):
    result={}
    res=requests.get(newsurl)
    res.encoding='utf-8'
    soup=BeautifulSoup(res.text,'html.parser')
    result['tittle']=soup.select('.main-title')[0].text
    timesource=soup.select('.date')[0].contents[0].strip()
    result['dt']=timesource
    result['article']=' '.join( [p.text.strip()  for p in soup.select('.article p')[:-1]])
    result['editor']=soup.select('.show_author')[0].text.lstrip('责任编辑:')
    result['comment']=getcomments(newsurl)
    return result

获取一则新闻的全部信息 

getNewsDetail('http://news.sina.com.cn/c/nd/2018-07-24/doc-ihftenhz6977167.shtml')

输出结果如下:

{'article': '原标题:外交部:睦邻友好是中菲关系的正确方向 据报道,23日,菲律宾总统杜特尔特发表国情咨文时提到菲中关系,回应了一段时间以来菲国内有关菲中关系的一些关切和质疑。杜高度评价中菲在打击跨国犯罪和禁毒等领域合作,并表示,中菲关系改善不代表菲放弃南海权益,双方正通过双边和多边渠道友好处理分歧。中国外交部发言人耿爽在今天(24日)的例行记者会上表示,中方注意到杜特尔特总统国情咨文中有关过去两年菲中关系持续改善,两国合作前所未有的积极评价。 耿爽表示,中方赞赏菲律宾*在杜特尔特总统领导下坚持独立自主外交政策,在相互平等、相互尊重的基础上发展同各国的正常关系和互利合作。2016年中菲关系转圜以来,双方各领域合作全面恢复并取得显著进展,为两国人民带来了实实在在的利益。安全合作是两国一大合作重点。中方坚定支持杜特尔特总统禁毒、反恐和打击跨国犯罪的努力,助力菲*维护和平安宁。近年来两国合作实践充分说明,睦邻友好是符合两国和两国人民利益的唯一选择,是我们应始终坚持的正确方向。 耿爽强调,杜特尔特总统就职以来,中菲就南海问题一直保持顺畅有效沟通,积极开展对话合作,维护了海上形势总体稳定。这一发展顺应两国人民的共同期盼,也为地区和平稳定作出重要贡献。中方愿同菲方一道,继续妥善管控分歧、聚焦务实合作,共同维护南海和平稳定。中方还将继续同包括菲律宾在内的东盟国家共建地区规则,推动“南海行为准则”磋商不断取得积极进展。(央视记者 申杨)',
 'comment': 109,
 'dt': '2018年07月24日 16:27',
 'editor': '霍宇昂 ',
 'tittle': '杜特尔特称中菲改善不代表放弃南海权益 中方回应'}
#分页连接网址
url='http://api.roll.news.sina.com.cn/zt_list?channel=news&\
cat_1=gnxw&cat_2==gdxw1||=gatxw||=zs-pl||=mtjj&level==1||=2&\
show_ext=1&show_all=1&show_num=22&tag=1&format=json&page=2&\
callback=newsloadercallback&_=1532430031835'
#获取一页新闻
parselistlinks(url)

python爬虫新浪新闻并存储数据到(mysql)数据库

 获取几页的新网

#{}内为新闻的页码
url='http://api.roll.news.sina.com.cn/zt_list?channel=news&\
cat_1=gnxw&cat_2==gdxw1||=gatxw||=zs-pl||=mtjj&level==1||=2&\
show_ext=1&show_all=1&show_num=22&tag=1&format=json&page={}&\
callback=newsloadercallback&_=1532430031835'
news_total=[]
for i in range(1,5):
    newsurl=url.format(i)
    newsary=parselistlinks(newsurl)
    news_total.extend(newsary)

爬取数据存入数据库

import pymysql
db = pymysql.connect('localhost','root','951010','student',charset='utf8')#连接数据库
cur = db.cursor()#创建游标
sqlc = '''
    create table news(
    id int(11) not null auto_increment primary key,
    article text not null,
    comment int(5) not null,
    dt varchar(20) not null,
    editor varchar(50) not null,
    tittle varchar(50) not null
    )
    '''
cur.execute(sqlc)#创建数据表

for new_total in news_total:
    article = new_total['article']
    comment = new_total['comment']
    dt = new_total['dt']
    editor = new_total['editor']
    tittle = new_total['tittle']
    sqli = '''insert into news(article,comment,dt,editor,tittle)
    values('%s','%d','%s','%s','%s')
    '''%(article,comment,dt,editor,tittle)
    try:
        cur.execute(sqli)#执行sql语句 ,插入数据  
        db.commit()# 提交到数据库执行
        print('导入数据库成功')
    except:
        db.rollback()# 如果发生错误则回滚
        print('shibai')
    cursor.close()#关闭游标

结束显示:

python爬虫新浪新闻并存储数据到(mysql)数据库

至此结束