import re
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
import random
import pandas as pd


def clickCounts(url):
    id = re.findall('\d+',url)[-1]
    clickUrl = "http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(id)
    clickStruct = requests.get(clickUrl).text
    clickCounts = int(clickStruct.split('.html')[-1][2:-3])
    return clickCounts

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



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'] = clickCounts(url)
    return newsDetail

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



def alist(listUrl):
    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['newsUrl'] = newsUrl
            newsDict['description'] = newsDesc
            newsList.append(newsDict)
    return newsList


listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
allnews = alist(listUrl)
for newtro in allnews:
    print(newtro)

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


for n in allnews:
    print(n)
#统计所爬取的新闻总数
print(len(allnews))



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


with sqlite3.connect('gzccnewsdb.sqlite') as db:
    df2 = pd.read_sql_query('SELECT * FROM gzccnewsdb',con=db)
df2

 

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

with sqlite3.connect('gzccnewsdb.sqlite') as db:
    df2 = pd.read_sql_query('SELECT * FROM gzccnews',con=db)
df2


!pip install PyMySQL

!pip install sqlalchemy

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄