• 理解爬虫原理


    这次作业的要求来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2881

    1. 简单说明爬虫原理

     (1)模拟计算机对服务器发起Request请求;

     (2)接收服务器的Response内容并解析、提取所需的信息。

     

    2. 理解爬虫开发过程

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

    浏览器工作原理的实质就是实现http协议的通讯,具体过程如下: 

         a. 连接 服务器通过一个ServerSocket类对象对8000端口进行监听,监听到之后建立连接,打开一个socket虚拟文件。
         b. 请求 创建与建立socket连接相关的流对象后,浏览器获取请求,为GET请求,则从请求信息中获取所访问的HTML文件名,向服务器发送请求。
          c. 应答 服务收到请求后,搜索相关目录文件,若不存在,返回错误信息  。若存在,则向HTML文件,进行加HTTP头等处理后响应给浏览器,浏览器解析html文件,若其中还包含图片,视频等请求,则浏览器再次访问web服务器,异常获取图片视频等,并对其进行组装显示出来。

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

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

    import requests
    res=requests.get('http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0322/11042.html')
    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" num=2019> This is link2</a>
     <p id="info">This is info
     </body>
    </html>'
    复制代码

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

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

    soup=BeautifulSoup(html_hjy,'html.parser')

    select(选择器)定位数据

    t = news.select('#title')
    l = news.select('.link')

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

    t=soup.select('h1')[0].text
    print(t)

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

    for i in range(len(soup.select('.link'))):
        d=soup.select('.link')[i].text
        print(d)

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

    info=soup.select('#info')[0].text
    print(info)

     

    3.提取一篇校园新闻的标题、发布时间、发布单位

    import requests
    import bs4
    from bs4 import BeautifulSoup
    #获取网页
    url="http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0320/11029.html";
    r=requests.get(url);
    r.encoding=r.apparent_encoding;
    text=r.text;
    #print(text);
    #解析网页
    soup=BeautifulSoup(text,"html.parser");
    #新闻标题
    title=soup.select(".show-title");
    print(title);
    #发布时间与发布单位
    time=soup.select(".show-info");
    print(time);

  • 相关阅读:
    洛谷
    洛谷
    洛谷
    洛谷
    洛谷
    模板
    模板
    模板
    洛谷
    模板
  • 原文地址:https://www.cnblogs.com/tianshizhao/p/10636396.html
Copyright © 2020-2023  润新知