zoukankan      html  css  js  c++  java
  • 爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离+网络爬虫基础练习

    可以新建一个用于练习的html文件,在浏览器中打开。

    1.利用requests.get(url)获取网页页面的html文件

    import  requests
    url="http://localhost:63342/bd/gzcc.html?_ijt=1s9ucf4k9asfpkjs4lhl0cg6vp"
    res=requests.get(url)
    res.encoding='utf-8'
    res.text

    2.利用BeautifulSoup的HTML解析器,生成结构树

    from  bs4 import BeautifulSoup
    soup=BeautifulSoup(res.text,'html.parser')

    3.找出特定标签的html元素

    soup.p #标签名,返回第一个

    soup.head

    soup.p.name #字符串

    soup.p. attrs #字典,标签的所有属性

    soup.p. contents # 列表,所有子标签

    soup.p.text #字符串

    soup.p.string

    soup.select(‘li')

    4.取得含有特定CSS属性的元素

    soup.select('#p1Node')

    soup.select('.news-list-title')

    5.练习:

    取出h1标签的文本
    取出a标签的链接
    取出所有li标签的所有内容
    取出第2个li标签的a标签的第3个div标签的属性

    取出一条新闻的标题、链接、发布时间、来源

    import requests
    from bs4 import BeautifulSoup
    res = requests.get('http://localhost:63342/demo/demo.html?_ijt=ckuj5j0gqtro8l1rnki5ik6j7f')
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    # 取出h1标签的文本
    print(soup.h1.text)
    # 取出a标签的链接
    print(soup.a['href'])
    # 取出所有li标签的所有内容
    for i in soup.select('li'):
        print(i)
    # 取出第2个li标签的a标签的第3个div标签的属性
    print(soup.select('li')[1].a.select('div')[2].attrs)
    # 取出一条新闻的标题、链接、发布时间、来源
    print('标题:'+soup.select('.news-list-title')[0].text)
    print('链接:'+soup.select('a')[2]['href'])
    print('发布时间:'+soup.select('.news-list-info')[0].span.text)
    print('来源:'+soup.select('.news-list-info')[0].select('span')[1].text)

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

    import requests
    from bs4 import BeautifulSoup
    
    res=requests.get("http://news.gzcc.cn/html/xiaoyuanxinwen/")
    res.encoding='utf-8'
    res.text
    
    soup=BeautifulSoup(res.text,'html.parser')
    
        if len(news.select('.news-list-title'))>0:
         title=news.select('.news-list-title')[0].text
         content=news.select('.news-list-description')[0].text
         href=news.a.attrs['href']
         print(title, href)
         resd = requests.get(href)
         resd.encoding = 'utf-8'
         resd.text
         soupd = BeautifulSoup(resd.text, 'html.parser')
         con=soupd.select('.show-content')[0].text # 获取文章内容
         print(con)
         time = soupd.select('.show-info')[0].text  #获取作者、时间
         dt=time.lstrip('发布时间:')[:19]
         print(dt)

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

    import requests
    from bs4 import BeautifulSoup
    
    res=requests.get("http://news.gzcc.cn/html/xiaoyuanxinwen/")
    res.encoding='utf-8'
    res.text
    
    soup=BeautifulSoup(res.text,'html.parser')
    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
         title=news.select('.news-list-title')[0].text
         href=news.a.attrs['href']
    
         resd = requests.get(href)
         resd.encoding = 'utf-8'
         resd.text
         soupd = BeautifulSoup(resd.text, 'html.parser')
         time = soupd.select('.show-info')[0].text  #获取作者、时间
         dt=time.lstrip('发布时间:')[:19]
         wt=time.split()[2].split("")[1]  #获取作者
         sf=time.split()[4].split("")[1] #获取来源
         tp=time.split()[5].split("")[1]  #获取摄影
       
         print(dt,wt,sf,tp)

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

         now=datetime.now()
         locale.setlocale(locale.LC_CTYPE, 'chinese')
         d='2018-04-04 09:35:00'
         dt=datetime.strptime(d,'%Y-%m-%d %H:%M:%S')
         st=now.strftime('%Y年%m月%d日 %H:35:00')

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

         url="http://news.gzcc.cn/html/2017/xibusudi_0906/8003.html"
         rm=re.match('http://news.gzcc.cn/html/2017/xibusudi_(.*).html',url).group(1).split('/')[1]
         rs=re.search('\_(.*).html',url).group(1).split('/')[1]
         rf=re.findall('\_(.*).html',url)[0].split('/')[1]

    5. 生成点击次数的Request URL

    6. 获取点击次数

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

    # 获取新闻点击次数
    def getNewsId(url):
        newsId = re.findall(r'\_(.*).html', newsUrl)[0][-4:]
        clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsId)
        clickRes = requests.get(clickUrl)
        # 利用正则表达式获取新闻点击次数
        clickCount = int(re.search("hits').html('(.*)');", clickRes.text).group(1))
        return clickCount

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

    # 获取新闻细节
    def getNewsDetail(newsUrl):
        resd = requests.get(newsUrl)
        resd.encoding = 'utf-8'
        soupd = BeautifulSoup(resd.text, 'html.parser')
    
        content = soupd.select('#content')[0].text
        info = soupd.select('.show-info')[0].text
        # 调用getNewsId()获取点击次数
        count = getNewsId(newsUrl)
        print(info)
        # 识别时间格式
        date = re.search('(d{4}.d{2}.d{2}sd{2}.d{2}.d{2})', info).group(1)
        # 识别一个至三个数据
        author = re.search('作者:((.{3}s){1,3})', info).group(1)
        check = re.search('审核:((.{3}s){1,3})', info).group(1)
        sources = re.search('来源:((.{3}s){1,3})', info).group(1)
        # 用datetime将时间字符串转换为datetime类型
        dateTime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
        # 利用format对字符串进行操作
        print('发布时间:{0}
    作者:{1}
    审核:{2}
    来源:{3}
    点击次数:{4}'.format(dateTime, author, check, sources, count))
        print(content)

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

    clickCount = int(re.search("hits').html('(.*)');", clickRes.text).group(1)
  • 相关阅读:
    [洛谷P3360]偷天换日
    [BZOJ3195]奇怪的道路
    [BAOJ3631]松鼠的新家
    [BZOJ4899]记忆的轮廓
    [BZOJ3940]Censoring
    P3303 [SDOI2013]淘金
    2019.8.5 NOIP模拟测试13 反思总结【已更新完毕】
    2019.8.3 NOIP模拟测试12 反思总结【P3938 斐波那契,P3939 数颜色,P3940 分组】
    2019.8.1 NOIP模拟测试11 反思总结
    洛谷P2178 [NOI2015]品酒大会
  • 原文地址:https://www.cnblogs.com/hhmk/p/8665240.html
Copyright © 2011-2022 走看看