作业的要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/3075
一.把爬取的内容保存取MySQL数据库
- import pandas as pd
- import pymysql
- from sqlalchemy import create_engine
- conInfo = "mysql+pymysql://user:passwd@host:port/gzccnews?charset=utf8"
- engine = create_engine(conInfo,encoding='utf-8')
- df = pd.DataFrame(allnews)
- df.to_sql(name = ‘news', con = engine, if_exists = 'append', index = False)
import pandas as pd import requests from bs4 import BeautifulSoup from datetime import datetime import re import time import random import sqlite3 import pymysql from sqlalchemy import create_engine coninfo='mysql+pymysql://root:lyh0523@localhost:3306/gzccnews?charset=utf8' engine = create_engine(coninfo,encoding='utf-8') 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(url)#点击次数 return newsDetail 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 allnews = [] for i in range(59,69): listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i) allnews.extend(alist(listUrl)) pd.Series(anews) newsdf=pd.DataFrame(allnews) for i in range(5): print(i) time.sleep(random.random()*3) print(newsdf) newsdf.to_csv('123.csv') #在本地项目下生成一个表格存储爬取新闻内容 newsdf.to_sql(name='news',con=engine,if_exists='append',index=False) conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='lyh0523',db='gzccnews',charset='utf8') with sqlite3.connect('gzccnewsdb.sqlite') as db: newsdf.to_sql('gzccnewsdb',db) #在本地项目下生成一个数据库存储爬取新闻内容