爬取全部的校园新闻

题目:

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

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

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

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

4.设置合理的爬取间隔

import time

import random

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

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 requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
import pandas as pd
import time
import random
import sqlite3

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‘)
    return dt

def anews(url):  # 从新闻url获取新闻详情: 字典,anews
    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

def alist(url):  # 从列表页的url获取新闻url:列表append(字典) alist
    res = requests.get(listUrl)
    res.encoding = ‘utf-8‘
    soup = BeautifulSoup(res.text, ‘html.parser‘)
    newsList = []
    for news in soup.select(‘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

newsUrl = ‘http://news.gzcc.cn/html/2005/xiaoyuanxinwen_0710/4.html‘
listUrl = ‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘
alist(listUrl)
alist(newsUrl)
res = requests.get(‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘)
res.encoding = ‘utf-8‘
soup = BeautifulSoup(res.text, ‘html.parser‘)

for news in soup.select(‘li‘):
    if len(news.select(‘.news-list-title‘)) > 0:
        newsUrl = news.select(‘a‘)[0][‘href‘]
        print(anews(newsUrl))

allnews = []
for i in range(97, 107):  # 爬取学号尾数开始的10个列表页
    listUrl = ‘http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html‘.format(i)
    allnews.extend(alist(listUrl))

print("allnewsLength={}".format(len(allnews)))
print(allnews)

res = requests.get(‘http://news.gzcc.cn/html/xiaoyuanxinwen/‘)
res.encoding = ‘utf-8‘
soup = BeautifulSoup(res.text, ‘html.parser‘)
for news in soup.select(‘li‘):
    if len(news.select(‘.news-list-title‘)) > 0:
        newsUrl = news.select(‘a‘)[0][‘href‘]
        print(anews(newsUrl))

s1 = pd.Series([100, 23, ‘bugingcode‘])
print(s1)
pd.Series(anews)
newsdf = pd.DataFrame(allnews)
for i in range(5):
    print(i)
    time.sleep(random.random() * 3)  # 设置爬取的时间间隔
    print(newsdf)

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

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

效果

保存的文件

css打开的结果

原文地址:https://www.cnblogs.com/hesz/p/10693323.html

时间: 2024-08-09 12:47:45

爬取全部的校园新闻的相关文章

(原)爬取辽宁科技大学相关新闻---python爬虫入门

有人说大部分python程序员都是通过爬虫入门的或者都是由爬虫喜欢上python的.还有大部分人学爬虫都喜欢拿自己学校的网站练手.我就是基于以上两点开始的... ok,开始,首先你需要一点python基础,一点点基础就可以,找一本薄薄的书过一遍,可以上这来找找 http://wiki.woodpecker.org.cn/moin/PyBooks 看书不爽,那你上这来看看,几道简简单单的题做过之后,顿觉一览众山小 http://www.pythontutor.com/ 咱们不是一边学爬虫,一边学p

Python3从零开始爬取今日头条的新闻【一、开发环境搭建】

Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Python3从零开始爬取今日头条的新闻[四.模拟点击切换tab标签获取内容] Python3从零开始爬取今日头条的新闻[五.解析头条视频真实播放地址并自动下载] 所谓爬虫,就是通过编程的方式自动从网络上获取自己所需的资源,比如文章.图片.音乐.视频等多媒体资源.通过一定的方式获取到html的内容,再通过

爬取学校官网新闻-bs与xpath的恩怨情仇

为了更好地学习<自然语言处理>这一门课,我们的老师叫我们组团去刷学校官网,我刚开始还以为很简单,事实证明,我错了,固执的凭借xpath去解析内容非常的难,还有我最后用bs4轻松解析,这个项目让我看清了xpath适合提取单个标签内的内容,而bs4明显适合去提取大段的内容,然后再通过join,strip,replace,split等内容就可以去掉转义字符,空格和转换为列表. 另外,老师也要求我们使用正则表达式,我用正则表达式去提取特定格式的时间还有在提取出来的文本内容中提取出最后一个括号内的内容,

python爬取凤凰网站的新闻,及其链接地址,来源,时间和内容,用selenium自动化和requests处理数据

1 import requests 2 from selenium import webdriver 3 import time 4 5 def grasp(urlT): 6 driver = webdriver.Chrome(r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe') #自动化测试程序工具本地所在地 7 resAll = [] #用于存储单条数据 8 rest = {} #用于存储单个数据 9 re

1)④爬取新浪军事新闻,并把内容存放到相应的文件夹中

1 __author__ = 'minmin' 2 #coding:utf-8 3 import re,urllib,sgmllib,os 4 5 #根据当前的url获取html 6 def getHtml(url): 7 page = urllib.urlopen(url) 8 html = page.read() 9 page.close() 10 return html 11 12 #根据html获取想要的文章内容 13 def func(str): 14 result= re.finda

爬取资讯网站的新闻并保存到excel

#!/usr/bin/env python#* coding:utf-8 *#author:Jacky from selenium.webdriver.common.keys import Keysfrom selenium import webdriverfrom bs4 import BeautifulSoupimport xlwt driver = webdriver.Firefox()driver.implicitly_wait(3)first_url = 'http://www.yid

爬取汽车之家新闻

a.首先伪造浏览器向某个地址发送HTTP请求,获取返回的字符串 import requestsresponse=requests.get(url='地址')#get请求 response.content #内容 response.encoding=apparent_encoding #检测编码形式,并设置编码 response.text #自动转码 b.通过Beautifulsoup4解析HTML格式字符串 from bs4 import BeautifulSoup soup = Beautif

py 爬取汽车之家新闻案例

``` import requests from bs4 import BeautifulSoup response = requests.get("https://www.autohome.com.cn/news/") # 1. content /text 的区别 # print(response.content) # content 拿到的字节 response.encoding = 'gbk' # print(response.text) # text 拿到的文本信息 soup

Python 利用 BeautifulSoup 爬取网站获取新闻流

0. 引言 介绍下 Python 用 Beautiful Soup 周期性爬取 xxx 网站获取新闻流: 图 1 项目介绍 1. 开发环境 Python: 3.6.3 BeautifulSoup:   4.2.0 , 是一个可以从HTML或XML文件中提取数据的Python库* ( BeautifulSoup 的中文官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ ) 2. 代码介绍 实现主要分为三个模块: 1. 计时