zoukankan      html  css  js  c++  java
  • 获取一篇新闻的全部信息

    作业要求来自于: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();

  • 相关阅读:
    程序员获取编程灵感的10 种方式
    修改Windows远程桌面3389端口
    修改Windows远程桌面3389端口
    JS 开发常用工具函数
    JS 开发常用工具函数
    IT公司老板落水,各部门员工怎么救
    IT公司老板落水,各部门员工怎么救
    如何优雅地给妹子优化电脑(Windows)?
    如何优雅地给妹子优化电脑(Windows)?
    程序员,你恐慌的到底是什么?
  • 原文地址:https://www.cnblogs.com/bufengdianbuchengmo/p/10639246.html
Copyright © 2011-2022 走看看