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

    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字符串,点击次数字符串。import requestfrom bs4 import BeautifulSoup

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

    url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(url)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text,'html.parser')

    #获取新闻详情
    def getNewDetail(Url):
    for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
    title = news.select('.news-list-title')[0].text
    description = news.select('.news-list-description')[0].text

    a = news.a.attrs['href']
    resd = requests.get(a)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')
    content = soupd.select('#content')[0].text
    s = soupd.select('.show-info')[0].text
    print("标题:",title)
    print("链接:",a)

    print("描述:",description)
    print("正文:",content)
    # print(s)

    #获取发布时间,作者,审核,来源,摄影等信息
    t = soupd.select('.show-info')[0].text[0:24].lstrip('发布时间:')
                #将字符串格式的发布时间转换成datetime类型
                dt = datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
    print("发布时间:",dt)
    print(soupd.select('.show-info')[0].text[30:36])
    print(soupd.select('.show-info')[0].text[38:45])
    print(soupd.select('.show-info')[0].text[46:53])
    print(soupd.select('.show-info')[0].text[56:61])
    getClickCount(a)

    break

    #h获取点击次数
    def getClickCount(Url):
    clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id=9183&modelid=80'
    c = requests.get(clickUrl).text.split('html')[-1].lstrip("'(").rstrip(")';")
    print("点击次数:",c)

    getNewDetail(url)

     

  • 相关阅读:
    iOS:Objective-C中Self和Super详解
    调试工具Instruments----Core Animation
    iOS开发之复制字符串到剪贴板
    Copy 和 mutableCopy
    TCP/IP,Http,Socket,XMPP的区别
    iOS程序中的内存分配 栈区堆区全局区(转)
    iOS常见算法(二分法 冒泡 选择 快排)
    老司机带你走进Core Animation
    C# 爬虫小程序
    C# 房贷计算器
  • 原文地址:https://www.cnblogs.com/wumeiying/p/8717790.html
Copyright © 2011-2022 走看看