代码改变世界

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

2018-04-10 20:53  216-陈文建  阅读(172)  评论(0编辑  收藏  举报

学会使用正则表达式

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

import requests
import re

r='^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$'
e='wzl201506110246@123.com'
if re.match(r,e):
    print(re.match(r,e).group(0))
    print('邮箱输入正确')
else:
    print('error')

  

 

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

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

  

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

news = '''The undersea vehicle, which is capable of diving to 4,500m, made its 50th dive on April 6 in the Indian Ocean, a part of China's 49th ocean expedition. Of the 50 dives , 35 were in the Indian Ocean and 15 in the South China Sea, according to China Ocean Mineral Resources R&D Association.In the southwest Indian Ocean alone, Qianlong II has traveled more than 2,000 km, they said.The submersible, which first went underwater in 2015, is used for exploring deepseamineral resources."Its operations have become more stable after 50 dives," said Xu Chunhui, a scientist tasked with equipping the submersible.Xu said a part of the upgrade will allow the submersible to work without the presence of its mother vessel1. A new unmanned monitoring device will track the submersible, freeing the mother vessel for other activities.'''
englishNews = re.split('[\s,.!?,"":;]',news)
print(englishNews)

  

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

import re
newsUrl = 'http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0401/9167.html'
a1 = re.search('\_(.*).html',newsUrl).group(1)
print(a1)

  

5. 生成点击次数的Request URL

import requests
res=requests.get('http://oa.gzcc.cn/api.php?op=count&id=9167&modelid=80')
res.encoding = 'utf-8'

  

6. 获取点击次数

a=res.text.split(".html")[-1].lstrip("(')").rstrip("');")
print(a)

  

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

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)
    count = requests.get(clickUrl).text.split('.html')[-1].lstrip("('").rstrip("');")
    return count
 
counts = getClickCount(newsUrl)
print(counts)

  

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

def getNewDetail(newsUrl):
    ress=requests.get(newsUrl)
    ress.encoding = 'utf-8'
    soups = BeautifulSoup(ress.text, 'html.parser')
    title = soups.select('.show-title')[0].text  # 标题
    info = soups.select('.show-info')[0].text             #连接
    dt = datetime.strptime(info.lstrip('发布时间:')[:19], '%Y-%m-%d %H:%M:%S') #发布时间
    if info.find('来源:')>0:
        source=info[info.find('来源:'):].split()[0].lstrip('来源:')
    else:
        source='none'
    # content=soup.select(".show-content")[0].text.strip()
    click=getClickCount(newsUrl)
    print(dt, title, newsUrl, source, click)
 
res=requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
for news in soup.select('li'):
    if len(news.select('.news-list-title')) > 0:
        ness=news.select('a')[0].attrs['href']#继续
        getNewDetail(ness)

  

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:
            a = news.select('a')[0].attrs['href']
            getNewDetail(a)
 
res = requests.get(newsUrl)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
n = int(soup.select('.a1')[0].text.rstrip('条'))
 
for i in range(n, n + 1):
    pageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/[].html'.format(i)
    getListPage(pageUrl)

  

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

def getPageN():
    res = requests.get(newsUrl)
    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/'
n = getPageN()
for i in range(n, n + 1):
    pageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/[].html'.format(i)
    getListPage(pageUrl)