1 importrequests2 from bs4 importBeautifulSoup3 from datetime importdatetime4 importre5 importpandas6 importsqlite37
8 url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
9 res =requests.get(url)10 res.encoding = 'utf-8'
11 soup = BeautifulSoup(res.text, 'html.parser')12
13 #给定单条新闻链接,返回点击次数
14 defgetclick(url):15 m=re.search(r'_(.*).html',url)16 newsid=m.group(1)[5:]17 clickurl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsid)18 resc=requests.get(clickurl).text19
20 #匹配任意位置的模式串,可以使用re.search() #re.match()只匹配位于字符串开始位置的模式串;
21 r=re.search(r'hits(.*)',resc).group(1)22 click=r.lstrip("').html('").rstrip("');")23 returnint(click)24
25 #print(getclick('http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1017/8338.html')) #图1
26
27 #给定单条新闻链接,返回新闻细节的字典
28 defgetdetail(url):29 resd=requests.get(url)30 resd.encoding='utf-8'
31 soupd=BeautifulSoup(resd.text,'html.parser')32 news={}33 news['url']=url34 news['title']=soupd.select('.show-title')[0].text35 info=soupd.select(".show-info")[0].text36 news['dt']=datetime.strptime(info.lstrip('发布时间:')[0:19],'%Y-%m-%d %H:%M:%S')##
37 news['source']=re.search('来源:(.*)点击',info).group(1).strip()38 #news['content']=soupd.select('.show-content')[0].text.strip()
39 news['click']=getclick(url)40 return(news)41 #print(getdetail('http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1017/8338.html')) #图2
42
43 #给定新闻列表页的链接,返回该页所有新闻的细节字典的列表
44 defonepage(pageurl):45 res=requests.get(pageurl)46 res.encoding='utf-8'
47 soup=BeautifulSoup(res.text,'html.parser')48 newsls=[]49 for news in soup.select('li'):50 if len(news.select('.news-list-title'))>0:51 newsls.append(getdetail(news.select('a')[0]['href']))52 return(newsls)53 #print(onepage('http://news.gzcc.cn/html/xiaoyuanxinwen/')) #图3
54
55 newstotal=[]56 gzccurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
57 newstotal.extend(onepage(gzccurl))58
59 res=requests.get(gzccurl)60 res.encoding='utf-8'
61 soup=BeautifulSoup(res.text,'html.parser')62 n=int(soup.select('.a1')[0].text.rstrip('条'))63 pages=n//10+1 #计算多少条新闻有多少页
64
65 for i in range(2,3):66 listurl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)67 newstotal.extend(onepage(listurl))#后面的每一个列表页(extend():列表1里接上列表2的内容)
68 #print(len(newstotal)) #20
69
70 df = pandas.DataFrame(newstotal)#创建DataFrame对象
71
72 #print(df.head()) #查看前几行的数据,默认前五行 #图4
73 #print(df['title']) #图5
74 #print(df[df.click>5000])#筛选
75
76 #保存到Excel表 #图6
77 df.to_excel('gzccnews.xlsx')78
79 #保存到数据库 #图7
80 with sqlite3.connect('gzccnews_db.sqlite') as db:81 df.to_sql('news_table',con = db)