使用正则表达式,取得点击次数,函数抽离

学会使用正则表达式

1. 用正则表达式判定邮箱是否输入正确。

import re
r='^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$'
e='3947653@qq.com'
if re.match(r,e):
    print(re.match(r,e).group(0))
else:
    print('error')

2. 用正则表达式识别出全部电话号码。

str='''版权所有:广州商学院   地址:广州市黄埔区九龙大道206号
学校办公室:020-82876130   招生电话:020-82872773
粤公网安备 44011602000060号    粤ICP备15103669号'''
print(re.findall('(\d{3,4})-(\d{6,8})',str))

  

3. 用正则表达式进行英文分词。re.split('',news)

news='''Passion is sweet Love makes weak You said you cherised freedom so You refused to let it go Follow your faith Love and hate never failed to'''
print(news.split())

  

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

import re
a='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html'
num=re.match('http://news.gzcc.cn/html/2018/xiaoyuanxinwen_(.*).html',a).group(1).split("/")[-1]
print(num)

  

5. 生成点击次数的Request URL

import re
a='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html'
num=re.match('http://news.gzcc.cn/html/2018/xiaoyuanxinwen_(.*).html',a).group(1).split("/")[-1]
url='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(num)
print(url)

  

6. 获取点击次数

import re
import requests
a='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html'
newId = re.search('\_(.*).html',a).group(1).split('/')[1]
clickUrl = "http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newId)
print(requests.get(clickUrl).text.split('.html')[-1].lstrip("('").rstrip("');"))

  

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

 

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

import re
import requests
from bs4 import BeautifulSoup
from datetime import datetime

def getClickCount(newsUrl):
    newId = re.search('\_(.*).html',newsUrl).group(1).split('/')[1]
    clickUrl = "http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newId)
    print("点击次数:"+requests.get(clickUrl).text.split('.html')[-1].lstrip("('").rstrip("');"))

def getNewDetail(newsUrl):
    resd = requests.get(newsUrl)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')
    print(t)
    print(newsUrl)
    info = soupd.select('.show-info')[0].text
    d = re.search('发布时间:(.*) \xa0\xa0 \xa0\xa0作者:', info).group(1)
    dt = datetime.strptime(d, '%Y-%m-%d %H:%M:%S')
    print('发布时间:{}'.format(dt))
    print('作者:' + re.search('作者:(.*)审核:', info).group(1))
    print('审核:' + re.search('审核:(.*)来源:', info).group(1))
    print('来源:' + re.search('来源:(.*)摄影:', info).group(1))
    print('摄影:' + re.search('摄影:(.*)点击', info).group(1))
    print('正文:'+soupd.select('.show-content')[0].text)

url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res=requests.get(url)
res.encoding="utf-8"
soup=BeautifulSoup(res.text,"html.parser")
for news in soup.select("li"):
    if len(news.select(".news-list-title")) > 0:
        t=news.select('.news-list-title')[0].text
        a = news.select('a')[0].attrs['href']  # 新闻链接
        getClickCount(a)
        getNewDetail(a)
        break

  

 

posted @ 2018-04-10 17:27  205李华秋  阅读(114)  评论(0编辑  收藏  举报