zoukankan      html  css  js  c++  java
  • Python爬虫(一)抓取指定的页面

    (以下是在windows环境下的操作,python版本为3)

    1.urllib库介绍

    官方文档上的解释是:

    urllib is a package that collects several modules for working with URLs

    简单的说就是用来处理url的,它包含以下几个模块:

    • urllib.request
    • urllib.request,打开并且读取url
    • urllib.error,包含了一些urllib.request引起的异常
    • urllib.parse,解析url
    • urllib.robotparser,解析robots.txt文件

    2.request模块

    The urllib.request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.

    这里,只需用到urllib.request模块,request模块包含了一些函数,用来处理打开的url。

    urlopen()

    urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

    该函数主要的参数就是url,可以是一个字符串也可以是一个request对象。
    函数返回一个可以作为文本管理器的对象,有如下方法:

    • geturl(),返回检索到的url资源,通常用于确定是否允许重定向
    • info(),返回页面的元信息,例如headers
    • getcode(),返回响应的http状态码

    为了清楚这些函数的作用是什么,我们运行如下python代码:

    import urllib.request
    url = "http://www.baidu.com"
    a = urllib.request.urlopen(url)
    print('----------type of a----------')
    print(type(a))
    
    print('----------geturl()----------')
    print(a.geturl())
    
    print('----------info()----------')
    print(a.info())
    
    print('----------getcode()----------')
    print(a.getcode())
    
    

    运行结果:

    3.抓取百度上关键词的搜索结果

    首先我们需要知道百度搜索的url,打开百度随便搜索一个词,就能在地址栏看到url

    得到url之后,剩下的就是对url进行爬取了,代码如下:

    # coding=utf-8
    # Created by dockerchen
    
    import urllib.request
    
    data = {}
    data['word'] = '网络安全'
    
    url_values = urllib.parse.urlencode(data)
    url = 'http://www.baidu.com/s?wd='
    
    full_url = url + url_values
    
    data = urllib.request.urlopen(full_url).read()
    data = data.decode('utf-8')
    print(data)
    

    urllib.parse.urlencode()可以将字符串转换为url格式的字符串,这里data进行转换后,我们可以得到wd=%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8的字符串。
    要是只想对一个字符串进行urlencode转换,可以使用urllib.parse.quote(),例如:

    >>> import urllib.parse
    >>> urllib.parse.quote('网络安全')
    '%E7%BD%91%E7%BB%9C%E5%AE%89%E5%85%A8'
    

    上面代码的输出结果其实就是爬取的百度页面搜索结果的源代码,之后要做的事,就是对爬取到的东西进行处理,来获取我们想要的数据

    参考:

    http://jecvay.com/2014/09/python3-web-bug-series1.html

  • 相关阅读:
    Shell脚本编程(三):shell参数传递
    Java代码里利用Fiddler抓包调试设置
    Shell脚本编程(二):shell变量
    Shell脚本编程(一):初识shell script
    JAVA使用SCANNER接收中文并输出时出现乱码
    RandomAccessFile类理解
    Vue(九):样式绑定v-bind示例
    Dockerfiles ENV和ARG的应用
    dockerfile中设置python虚拟环境+gunicorn启动
    Docker容器 暴露多个端口
  • 原文地址:https://www.cnblogs.com/dockerchen/p/6786350.html
Copyright © 2011-2022 走看看