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

学会使用正则表达式

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

import re
r = '^\w+@\w+.\w+'
e = 'sadf4534@qq.com'
if(re.match(r, e)):
    print(re.match(r, e).group(0))
else:
    print('error')

  

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

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

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

import re
str='''Floating Amidst The Stars Stargazing Meditation Since the beginning 
      of time,humans have gazed at the stars in the night sky with awe, seeking 
      in their luminosity everything from answers to inspiration to guidance.'''
print(re.split('[\s,.?\-]+',str)) 

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

5. 生成点击次数的Request URL

6. 获取点击次数

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

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

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

def getNewsDetail(newsUrl):
    res = requests.get(newsUrl)
    res.encoding = 'utf-8'
    Ssoup = BeautifulSoup(res.text,'html.parser')

    title = Ssoup.select('.show-title')[0].text
    info = Ssoup.select('.show-info')[0].text
    dt = datetime.strptime(info.lstrip('发布时间:')[0:19],'%Y-%m-%d %H:%M:%S')
    source = info[info.find('来源:'):].split()[0].lstrip('来源:')
    content = Ssoup.select('.show-content')[0].text.strip()
    click = getClickCount(newsUrl)
    print(dt,title,newsUrl,source,click)

  

9. 取出一个新闻列表页的全部新闻 包装成函数def getListPage(pageUrl):

def getListPage(pageUrl):
        res = requests.get(pageUrl)
        res.encoding = 'utf-8'
        soup = BeautifulSoup(res.text, 'html.parser')
        for news in soup.select("li"):
            if len(news.select(".news-list-title"))>0:  #排除为空的li
                a = news.select('a')[0].attrs['href']
                getNewsDetail(a)

  

10. 获取总的新闻篇数,算出新闻总页数包装成函数def getPageN():

def getPageN():
    res = requests.get(pageUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    n = int(soup.select('.a1')[0].text.rstrip('条'))

    return (n//10+1) 

11. 获取全部新闻列表页的全部新闻详情。

pageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
getListPage(pageUrl)
n = getPageN()
for i in range(2,n+1):
    print(i)
    listPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    getListPage(listPageUrl)

  

posted @ 2018-04-10 21:45  200张德标  阅读(107)  评论(0编辑  收藏  举报