python-爬取网络新闻

  1. 获取单条新闻的#标题#链接#时间#来源#内容 #点击次数,并包装成一个函数。
  2. 获取一个新闻列表页的所有新闻的上述详情,并包装成一个函数。
  3. 获取所有新闻列表页的网址,调用上述函数。
  4. 完成所有校园新闻的爬取工作。
  5. 完成自己所选其他主题相应数据的爬取工作。
 1 import requests
 2 import re
 3 from bs4 import BeautifulSoup
 4 url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
 5 res=requests.get(url)
 6 res.encoding='utf-8'
 7 soup=BeautifulSoup(res.text,'html.parser')
 8 
 9 #获取点击次数
10 def getclick(newurl):
11     id=re.search('_(.*).html',newurl).group(1).split('/')[1]
12     clickurl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id)
13     click=int(requests.get(clickurl).text.split(".")[-1].lstrip("html('").rstrip("');"))
14     return click
15 
16 #获取网页内容
17 def getonpages(listurl):
18     res=requests.get(listurl)
19     res.encoding='utf-8'
20     soup=BeautifulSoup(res.text,'html.parser')
21     
22     for news in soup.select('li'):
23         if len(news.select('.news-list-title'))>0:
24             title=news.select('.news-list-title')[0].text #标题
25             time=news.select('.news-list-info')[0].contents[0].text#时间
26             url1=news.select('a')[0]['href'] #链接
27             source=news.select('.news-list-info')[0].contents[1].text#来源
28             description=news.select('.news-list-description')[0].text #内容
29 
30             resd=requests.get(url1)
31             resd.encoding='utf-8'
32             soupd=BeautifulSoup(resd.text,'html.parser')
33             detail=soupd.select('.show-content')[0].text
34 
35             click=getclick(url1) #调用点击次数
36             print(title,url1,click)
37 
38 
39 
40 count=int(soup.select('.a1')[0].text.rstrip(""))
41 pages=count//10+1
42 for i in range(2,4):
43     pagesurl="http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html".format(i)
44     getonpages(pagesurl)

原文地址:https://www.cnblogs.com/maykok/p/7652052.html