网络爬虫入门

一: 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'))
    

    结果如图:
    抓取的python官网源代码

    查看类型:

    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'))
    

    结果同上

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值