• 爬虫的概述以及使用(urllib发送请求)


    一、爬虫概述

      爬虫,就是给网站发起请求,并从响应中提取需要的数据的自动化程序。

      1.发起请求,获取响应

        通过http库,对目标站点进行请求。等同于自己打开浏览器,输入网址

        通常库:urllib、urllib3、requests

        服务器会返回请求的内容,一般为:html、二进制文件(视频,音频)、文档,json字符串等

      2.解析内容

        寻找自己需要的信息,就是利用正则表达式或者其他库提取目标信息

        常用库:re、beautifulsoup4

      3.保存数据

        将解析得到的数据持久化到文件或者数据库中

    二、使用urllib发送请求

      request.urlopen()                                                                                # 这是最基本的反爬措施                                               

           from urllib import request                                                                       from urllib import request  

      url = "http://www.baidu.com"                   url = "http://www.dianping.com"

      res = request.urlopen(url)  #访问url并获取响应           header = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"}

      print(res.geturl())  #获取主机地址                 req = request.Request(url,headers=header)

      print(res.getcode())  #获取请求状态码               res = request.urlopen(rep) #访问url并获取响应

      print(res.getinfo())  #获取响应头                   print(res.geturl())  #获取主机地址

      html = res.read() #获取的是字节形式的内容              print(res.getcode())  #获取请求状态码

      html.decode("utf-8") #解码                    print(res.getinfo())  #获取响应头 

      print(html)                            html = res.read() #获取的是字节形式的内容

                                        html.decode("utf-8") #解码

          运行程序中的错误以及解决方法:(上面直接用utf-8进行解码没有成功报错了,改成下面这样就好了)

             from urllib import request

       from io import BytesIO
       import gzip

       url = "http://www.baidu.com"
       res = request.urlopen(url) #获取响应

       print(res.info()) #响应头
       print(res.getcode())
       print(res.geturl())

       html = res.read()
       buff = BytesIO(html)
       f = gzip.GzipFile(fileobj=buff)
       htmls = f.read().decode('utf-8')
       #html = html.decode("utf-8")
       print(htmls)

            下面爬虫得到的结果如图:

  • 相关阅读:
    UVALive-3989 Ladies' Choice (稳定婚姻问题)
    UVA-11383 Golden Tiger Claw (KM算法)
    UVA-10816 Travel in Desert (最小瓶颈最短路)
    UVA-10369 Arctic Network (最小生成树)
    内核态信号量(todo)
    openBMC(todo)
    uboot on qemu
    install ubuntu iso on windows
    在qemu上运行linux
    todo:register_sysctl_table
  • 原文地址:https://www.cnblogs.com/renleiblog/p/12587665.html
Copyright © 2020-2023  润新知