爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离

1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文、show-info。

2. 分析info字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。

3. 将字符串格式的发布时间转换成datetime类型

4. 使用正则表达式取得新闻编号

5. 生成点击次数的Request URL

6. 获取点击次数

7. 将456步骤定义成一个函数 def getClickCount(newsUrl):

8. 将获取新闻详情的代码定义成一个函数 def getNewDetail(newsUrl):

9. 尝试用使用正则表达式分析show info字符串,点击次数字符串。

 1 import requests
 2 from bs4 import BeautifulSoup
 3 from datetime import datetime
 4 import re
 5 res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
 6 res.encoding = 'utf-8'
 7 soup = BeautifulSoup(res.text, 'html.parser')
 8 
 9 
10 # 获取新闻点击次数
11 def getNewsId(url):
12     #使用正则表达式获得新闻编号
13     newsId = re.findall(r'\_(.*).html', url)[0][-4:]
14     #生成点击次数的Request URL
15     clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsId)
16     clickRes = requests.get(clickUrl)
17     # 利用正则表达式获取新闻点击次数
18     clickCount = int(re.search("hits'\).html\('(.*)'\);", clickRes.text).group(1))
19     return clickCount
20 
21 
22 
23 def getNewDetail(newsUrl):
24     # 读取新闻详情
25     resDescript = requests.get(newsUrl)
26     resDescript.encoding = "utf-8"
27     soupDescript = BeautifulSoup(resDescript.text, 'html.parser')
28 
29     content = soupDescript.select(".show-content")[0].text  # 正文
30     info = soupDescript.select(".show-info")[0].text  # info相关内容
31     time = re.search("发布时间:(.*) \xa0\xa0 \xa0\xa0作者:", info).group(1)
32     author = re.search("作者:(.*)\xa0\xa0审核:", info).group(1)
33     right = re.search("审核:(.*)\xa0\xa0来源:", info).group(1)
34     resource = re.search('来源:(.*)\xa0\xa0\xa0\xa0摄影:', info).group(1)
35     video = re.search("摄影:(.*)\xa0\xa0\xa0\xa0点击:", info).group(1)
36     # 调用getNewsId()获取点击次数
37     count = getNewsId(newsUrl)
38     # 用datetime将时间字符串转换为datetime类型
39     dateTime = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
40 
41     print('标题' + ': ' + title)
42     print('概要' + ': ' + description)
43     print('链接' + ': ' + a)
44     print('正文' + ' :' + content)
45     print('发布时间:{0}\n作者:{1}\n审核:{2}\n来源:{3}\n摄影:{4}\n点击次数:{5}'.format(dateTime, author, right, resource, video,count))
46     print("\n")
47 
48 
49 
50 for s in soup.select("li"):
51     if len(s.select(".news-list-title"))>0:
52         title = s.select(".news-list-title")[0].text #新闻标题
53         description = s.select(".news-list-description")[0].text #新闻描述
54         a = s.a.attrs["href"] #观看新闻详情
55         getNewDetail(a)
56         break

 

posted @ 2018-04-03 15:11  201506110167陈广鹏  阅读(443)  评论(0编辑  收藏  举报