网络爬虫入门

一: Urllib的基础使用

  • Urllib模块
    urllib它是Python的内置的Htpp请求库,有四个模块
    1.request : 它是最基本的HTTP请求模块,可以用来模拟发送请求
    2.error: 异常处理模块。
    3.parse:一个工具模块,提供了许多URL处理方法
    4.robotparser: 主要是用来识别网站的robots.txt文件,然后来判断哪些网站可以爬…等

  • 发送请求
    urllib.request.urlopen() 这个方法可以够造HTTP请求方法,同时还带有处理授权验证、重定向、浏览器Cookies以及其他内容
    现在我们来抓取Python官网:

    import urllib.request
    response = urllib.request.urlopen('https://www.python.org/')
    print(response.read().decode('utf-8'))
    

    结果如图:
    网络爬虫入门

    查看类型:

    print(type(response))
    

    查看响应状态码:
    查看响应的头信息:
    传递一个参数server获得的响应头中的server值:

    print(response.status)
    print(response.getheaders())
    print(response.getheader('server'))
    

    结果如下:
    网络爬虫入门

  • data参数:
    data参数是可选的,如果添加参数就要通过bytes()方法来转换,如果传递了这个参数,则它的请求不再是GET,而是POST
    代码如下:

    import urllib.request
    import urllib.parse
    data = bytes(urllib.parse.urlencode({'world' : 'hello'}), encoding='utf-8')
    response = urllib.request.urlopen('https://httpbin.org/post', data=data)
    print(type(response))
    print(response.read())
    

    结果如下:
    网络爬虫入门

  • timeout 参数:
    timeout参数用于设置超时时间,单位为秒,超出这个设置时间还没有响应就会抛出异常
    代码如下:

    import urllib.request
    response = urllib.request.urlopen('https://www.python.org/', timeout=1)
    print(response.read())
    
    

    运行结果如下:
    网络爬虫入门
    也可以同try except语句来实现:
    代码如下:

    import urllib.request
    import socket
    import urllib.error
    
    
    try:
        response = urllib.request.urlopen('http:  //httpbin.org/get', timeout=1)
    except urllib.error.URLError as e:
        if isinstance(e.reason, socket.timeout):
            print('time out')
        else:
            print(response.read())
    
    

    运行结果:
    time out

  • Request
    使用代码:

    import urllib.request
    
    
    request = urllib.request.Request('https: //python.org ')
    response = urllib.request.urlopen(request)
    
    print(response.read().decode('utf-8'))
    

    结果同上

本期就先写到这里 ,下期再见!