python爬虫学习第一天

今天开始学习python网络爬虫,写个博客作为笔记以及自己的学习过程以监督自己。

今天学习了urllib这个python包的一部分内容,主要是urllib.request

内容简记:

urllib.request.urlopen()详解
利用以上最基本的urlopen()方法,我们可以完成最基本的简单网页的GET请求抓取。

data参数
data参数是可选的,如果要添加data,它要是字节流编码格式的内容,即bytes类型,通过bytes()函数可以进行转化,另外如果你传递了这个data参数,它的请求方式就不再是GET方式请求,而是POST。

timeout参数
timeout参数可以设置超时时间,单位为秒,意思就是如果请求超出了设置的这个时间还没有得到响应,就会抛出异常,如果不指定,就会使用全局默认时间。它支持HTTP、HTTPS、FTP请求。

自作练习(简单的把样例代码自己敲一遍):

练习1简单爬网页元素

import urllib.request
import urllib.parse
import urllib.error
import socket
response = urllib.request.urlopen('https://www.python.org')
print(response.read().decode('utf-8'))
print(type(response))
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))

练习2urlopen函数data参数

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

练习3 urlopen函数timeout参数

response = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(response.read())

练习4 捕获timeout异常

try:
    response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
    pass
except Exception as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT!')
        pass
    pass

今天挺忙的只敲了这些,之前写python不多,敲得有些生疏

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值