爬虫第一天,urllib库中的URLopen

爬虫

基本流程

1、发起请求

requests
GET or import

response

①浏览器发送消息给该网址所在服务器HTTP Requests
②服务器根据内容,做出相应处理,把消息回传给浏览器HTTP Response
③浏览器收到Response信息后,进行解析

2、解析内容
3、获取相应内容
4、保存数据

Urllib库

请求模块
异常处理
解析模块

启动jupyter notebook
打开cmd cd
步骤①
找到python文件下的Scripts,输入jupyter notebook回车

回车后出现的页面
新建

python3

URLopen

代码

urllib.request.urlopen(url,data+None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))

如图所示
在这里插入图片描述
ctrl+enter收起运行结果

import urllib.parse
import urllib.request

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

在这里插入图片描述

import urllib.request

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

在这里插入图片描述

import socket
import urllib.request
import urllib.error

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

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值