爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | import requests from bs4 import BeautifulSoup import re from datetime import datetime def soup1(url): req = requests.get(url) req.encoding = 'utf-8' soup = BeautifulSoup(req.text, 'html.parser' ) return soup def getNum(urls): html_id = list () j = 0 for i in urls: html_id.append(re.search( 'http://news.gzcc.cn/html/2018/xiaoyuanxinwen_(.*).html' , i).group( 1 ).split( '/' )[ - 1 ]) down_url = 'http://oa.gzcc.cn/api.php?op=count&id=' + html_id[j] + '&modelid=80' reqd = requests.get(down_url) down_num.append(re.search( "\('#hits'\).html\('(.*)'\);" , reqd.text).group( 1 )) j = j + 1 return down_num soup = soup1( 'http://news.gzcc.cn/html/xiaoyuanxinwen' ) li_list = soup.select( 'li' ) title = list () a = list () for new in li_list: if ( len (new.select( '.news-list-text' )) > 0 ): title.append(new.select( '.news-list-text' )[ 0 ].select( '.news-list-title' )[ 0 ].text) a.append(new.a.attrs[ 'href' ]) info_list = list () con_list = list () for curl in a: con_soup = soup1(curl) con_list.append(con_soup.select( '#content' )[ 0 ].text) info_list.append(con_soup.select( '.show-info' )[ 0 ].text.split( "\xa0\xa0" )) cs = list () for i in range ( len (con_list)): cs.append(''.join(con_list[ 0 ])) down_num = list () down_num = getNum(a) for i in range ( len (info_list)): print ( '标题:' + title[i]) print ( '链接:' + a[i]) for j in range ( len (info_list[i])): if ( len (info_list[i][j]) > 0 and info_list[i][j] ! = ' ' ): if (j ! = len (info_list[i]) - 1 ): print (info_list[i][j]) else : print (info_list[i][j].rstrip( '次' ), down_num[i], '次' ) print (cs[i]) |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步