爬取全部的校园新闻

作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3002

0.从新闻url获取点击次数,并整理成函数

  • newsUrl
  • newsId(re.search())
  • clickUrl(str.format())
  • requests.get(clickUrl)
  • re.search()/.split()
  • str.lstrip(),str.rstrip()
  • int
  • 整理成函数
  • 获取新闻发布时间及类型转换也整理成函数

1.从新闻url获取新闻详情: 字典,anews

代码如下:

#获取一条新闻的详情
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re

def click(url):
    id = re.findall('(d{1,5})',url)[-1]#返回所有匹配的字符串的字符串列表的最后一个
    clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id)
    resClick = requests.get(clickUrl)
    newsClick = int(resClick.text.split('.html')[-1].lstrip("('").rstrip("');"))
    return newsClick
#时间
def newsdt(showinfo):
    newsDate = showinfo.split()[0].split(':')[1]
    newsTime = showinfo.split()[1]
    newsDT = newsDate+' '+newsTime
    dt = datetime.strptime(newsDT,'%Y-%m-%d %H:%M:%S')#转换成datetime类型
    return dt
#内容
def anews(url):
    newsDetail = {}
    res = requests.get(url)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text,'html.parser')
    newsDetail['newsTitle'] = soup.select('.show-title')[0].text#题目
    showinfo = soup.select('.show-info')[0].text
    newsDetail['newsDT'] = newsdt(showinfo)#时间
    newsDetail['newsClick'] = click(newsUrl)#点击次数
    return newsDetail

newsUrl = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0404/11155.html'
print(anews(newsUrl))

  

运行结果:

2.从列表页的url获取新闻url:列表append(字典) alist

代码如下:

def alist(url):
    res = requests.get(listUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    newsList = []
    for news in soup.select('li'):#获取li元素
        if len(news.select('.news-list-title'))>0:#如果存在新闻题目
            newsUrl = news.select('a')[0]['href']#获取新闻的链接
            newsDesc = news.select('.news-list-description')[0].text#获取摘要文本
            newsDict = anews(newsUrl)#通过链接获取题目时间点击数
            newsDict['description'] = newsDesc
            newsList.append(newsDict)#把每个新闻的信息放进字典扩展到列表里
    return newsList
listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
print(alist(listUrl))

 运行结果:

 

3.生成所页列表页的url并获取全部新闻 :列表extend(列表) allnews

代码如下:

allnews = []
for i in range(50,60):
    listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    allnews.extend(alist(listUrl))
print(len(allnews))
print(allnews)

 运行结果:

 

*每个同学爬学号尾数开始的10个列表页

4.设置合理的爬取间隔

import time

import random

time.sleep(random.random()*3)

代码如下:

for i in range(5):
    print(i)
    time.sleep(random.random() * 3)  # 设置爬取的时间间隔
    print(newsdf)

  

5.用pandas做简单的数据处理并保存

保存到csv或excel文件 

newsdf.to_csv(r'F:duym爬虫gzccnews.csv')

保存到数据库

import sqlite3
with sqlite3.connect('gzccnewsdb.sqlite') as db:
    newsdf.to_sql('gzccnewsdb',db)

代码如下:

import pandas as pd
import time
import random
import sqlite3
pd.Series(allnews)#保存文件
newsdf = pd.DataFrame(allnews)
for i in range(5):
    print(i)
    time.sleep(random.random() * 3)  # 设置爬取的时间间隔
    print(newsdf)

newsdf.to_csv(r'D:Downloadgzcc.csv', encoding='utf_8_sig')  # 保存成csv格式,为避免乱码,设置编码格式为utf_8_sig

with sqlite3.connect(r'D:Downloadgzccnewsdb2.sqlite') as db:  # 保存文件为sql
    newsdf.to_sql('gzccnewsdb2', db)

 运行结果:

 

原文地址:https://www.cnblogs.com/hycolins/p/10696529.html