zoukankan      html  css  js  c++  java
  • 理解爬虫原理

    1. 简单说明爬虫原理

    1、向服务器发起请求

    2、获取响应内容 

    3、解析内容

    4、保存内容 

    2. 理解爬虫开发过程

    1).简要说明浏览器工作原理;

    浏览器的主要功能是向服务器发出请求,在浏览器中展示选择的网路资源,一般资源就是HTML文档,也可以是PDF, IMGAGE,或者其他类型,资源的位置由用户使用URI(统一资源表示符)指定。

    2).使用 requests 库抓取网站数据

    requests.get(url) 获取校园新闻首页html代码

    import requests
    url='http://news.gzcc.cn/html/2019/meitishijie_0225/10895.html'
    res = requests.get(url)
    res.encoding='utf-8'
    res.text

    3).了解网页

    写一个简单的html文件,包含多个标签,类,id

    <html> 
        <body> 
              <h1 id="title">Hello</h1> 
              <a href="#" class="link"> This is link1</a>
              <a href="# link2" class="link" qao=123> This is link2</a>
        </body> 
    </html> '

    4).使用 Beautiful Soup 解析网页;

    通过BeautifulSoup(html_sample,'html.parser')把上述html文件解析成DOM Tree

    select(选择器)定位数据

    找出含有特定标签的html元素

    找出含有特定类名的html元素

    找出含有特定id名的html元素

    <html> 
        <body> 
              <h1 id="title">Hello</h1> 
              <a href="#" class="link"> This is link1</a>
              <a href="# link2" class="link" qao=123> This is link2</a>
        </body> 
    </html> '
    soups = BeautifulSoup(html_sample,'html.parser')
    a1 =soups.a
    a = soups.select('a')
    h = soups.select('h1')
    t = soups.select('#title')
    l = soups.select('.link')

    3.提取一篇校园新闻的标题、发布时间、发布单位、作者、点击次数、内容等信息

    如url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html'

    要求发布时间为datetime类型,点击次数为数值型,其

    temp=requests.get("http://news.gzcc.cn/html/2019/meitishijie_0225/10895.html")
    temp.encoding='utf-8'
    
    soups=BeautifulSoup(temp.text,'html.parser')
    title=soups.select('.show-title')[0].text
    content_array=soups.select('.show-info')[0].text.split()
    content=soups.select('#content')
    publish_date=content_array[0].split('发布时间:')[1]
    
    actor=content_array[2]
    click=requests.get("http://oa.gzcc.cn/api.php?op=count&id=11095&modelid=80").text.split('.html')[-1].replace("(","").replace(")","").replace("'","").replace(";","")
    date=datetime.strptime(publish_date+' '+content_array[1],'%Y-%m-%d %H:%M:%S')
    
    print("标题:"+title)
    print("点击次数:"+click)
    print(actor)
    print(date)
    print("内容:"+content[0].text)

    演示:

     

  • 相关阅读:
    python day 6 time 库
    python day 5 基本数据类型
    20191206《信息安全导论》第六周学习总结
    第十节 数据流重定向
    第九节 简单的文本处理
    第八节 命令执行顺序控制与管道
    第七节 文件系统操作与磁盘管理
    第六节 文件打包与解压缩
    第五节 环境变量与文件查找
    第四节 Linux目录文件及文件基本操作
  • 原文地址:https://www.cnblogs.com/gzcchyf/p/10636621.html
Copyright © 2011-2022 走看看