爬取所有校园新闻
1.获取单条新闻的#标题#链接#时间#来源#内容 #点击次数,并包装成一个函数。
2.获取一个新闻列表页的所有新闻的上述详情,并包装成一个函数。
3.获取所有新闻列表页的网址,调用上述函数。
4.完成所有校园新闻的爬取工作。
import requests
from bs4 import BeautifulSoup
import re
#获取一个新闻列表页的所有新闻的上述详情,并包装成一个函数。
def getclick(newurl):
id=re.search('_(.*).html',newurl).group(1).split('/')[1]
clickurl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id)
click=int(requests.get('http://oa.gzcc.cn/api.php?op=count&id=8249&modelid=80').text.split('.')[-1].lstrip("html('").rstrip("');"))
return click
#获取单条新闻的#标题#链接#时间#来源#内容 #点击次数,并包装成一个函数。
def getnews(listurl):
res=requests.get(listurl)
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
for news in soup.select('li'):
if len(news.select('.news-list-title'))>0:
title = news.select('.news-list-title')[0].text
url=news.select('a')[0]['href']
time=news.select('.news-list-info')[0].contents[0].text
source=news.select('.news-list-info')[0].contents[1].text
resd=requests.get(url)
resd.encoding='utf-8'
soupd = BeautifulSoup(resd.text,'html.parser')
detail=soupd.select('.show-content')[0].text
count=getclick(url)
print('点击次数:',count,'\n标题:',title,'\n链接:',url,'\n时间:',time,'\n来源:',source,'\n内容:',detail,'\n')
#获取所有新闻列表页的网址,调用上述函数。
res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding='utf-8'
soup = BeautifulSoup(res.text,'html.parser')
s=int(soup.select('.a1')[0].text.rstrip('条'))
ss=s//10+1
for i in range(1,s):
gzccurl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
getnews(gzccurl)
运行结果:

5.完成自己所选其他主题相应数据的爬取工作。
(将上次任务丰富并包装成一个函数并调用)
import requests
from bs4 import BeautifulSoup
def get(url):
res = requests.get(url)
res.encoding='utf-8'
soup = BeautifulSoup(res.text,'html.parser')
for news in soup.select('li'):
if len(news.select('.text-ellipsis'))>0:
title=news.select('a')[0].text
url=news.select('a')[0]['href']
time=news.select('li')[0].text
resd=requests.get(gurl+url)
resd.encoding='utf-8'
soupd = BeautifulSoup(resd.text,'html.parser')
detail=soupd.select('.t-indent')[0].text
print('时间:',time,'\n链接:',gurl+url,'\n',title,'\n',detail,'\n\n')
gurl = 'https://gupiao.baidu.com'
gpurl = gurl+'/stock/sz300023.html/'
print(get(gpurl))
运行结果:


浙公网安备 33010602011771号