• 获取一篇新闻的全部信息


    作业要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2894

    给定一篇新闻的链接newsUrl,获取该新闻的全部信息

    标题、作者、发布单位、审核、来源

    发布时间:转换成datetime类型

    点击:

    • newsUrl
    • newsId(使用正则表达式re)
    • clickUrl(str.format(newsId))
    • requests.get(clickUrl)
    • newClick(用字符串处理,或正则表达式)
    • int()

    整个过程包装成一个简单清晰的函数。

    尝试去爬取一个你感兴趣的网页。

    import requests
    import re
    from bs4 import BeautifulSoup
    
    #获取html页面
    def getHtml(url):
        r=requests.get(url);
        r.status_code;
        r.encoding=r.apparent_encoding;
        html=r.text;
        #print(html);
        return html;
    
    #获取新闻的信息
    def newsInfo(html):
      soup=BeautifulSoup(html,"html.parser");
      title=soup.select(".news_title"); #获取新闻的标题
      oneInfo=soup.select(".news_about");
      time=re.findall("</p>.*<p>(.*?)<span>",str(oneInfo[0]),re.S) #获取新闻的发布时间
      source=re.findall("来源:(.*?)</span>",str(oneInfo[0]),re.S) #获取新闻的来源
      twoInfo=soup.select(".news_txt");
      writer=re.findall("</div>文:(.*?)<br/>",str(twoInfo[0]),re.S) #获取新闻的作者
      news=twoInfo[0].text; #获取新闻的内容
      return title,time,source,writer,news;
    
    #获取新闻编号
    def newsid(url):
        newsID=re.findall('(d{7})',url)[-1]
        return newsID;
    
    #主方法
    def main():
        url = "https://www.thepaper.cn/newsDetail_forward_3231590";
        html = getHtml(url);
        newsID=newsid(url);
        title, time, source, writer,news= newsInfo(html);
        print("新闻编号:" + newsID);
        print("标题:"+str(title[0].text).strip(" "));
        print("发布时间:" + str(time[0]).strip("
    ").strip(" "));
        print("来源:" + str(source[0]).strip(" "));
        print("作者:" + str(writer [0]).strip(" "));
        print("新闻内容:" + news.strip(" "));
    
    main();

  • 相关阅读:
    c# DataTable 转为 List 类型
    .net配置文件读取
    文件重命名(递归)
    sharepoint 网站创建
    Sharepoint添加顶部导航菜单
    .net sharepoint文档库操作
    c#下载共享文件夹下的文件并记录错误日志
    JS命名空间实例
    js时间处理函数
    模块
  • 原文地址:https://www.cnblogs.com/bufengdianbuchengmo/p/10639246.html
Copyright © 2020-2023  润新知