urllib爬虫模块的方法使用-1

目录列表

发送请求
响应的处理方式

urllib.parse

import urllib.parse 提供了很多URL处理方法, 比如:拆分,解析,合并

urllib.error

import urllib.error 异常处理模块,保证程序不会报错

urllib.request的导入

urllib中request模块,实现请求的发送并且得到响应
import urllib.request

传递的参数,除了url必传之外,其他都可选参数
在这里插入图片描述

data参数

POST请求方式,模拟form表单提交可以使用
示例代码

import urllib.request
import urllib.parse

data = bytes(urllib.parse.urlencode({"word": "hello"}), encoding="utf-8")  # bytes数据类型
response = urllib.request.urlopen("http://httpbin.org/post", data=data)
print(response.read())

如果使用data数据,必须转化为bytes字节流类型.如果传递这个data参数,请求方式为post方式

timeout参数

timeout参数设置超时时间,单位为秒。如果超过了设置时间,程序抛出异常
示例代码:

response = urllib.request.urlopen("http://httpbin.org/post", data=data, timeout=0.1)

发送请求

响应对象 = urllib.request.urlopen("请求路径")

示例代码:
请求的是python的官网

import urllib.request
response = urllib.request.urlopen("https://www.python.org/")
print(type(response))
print("="*30)
print(response.read().decode())

响应对象

示例代码:

import urllib.request
response = urllib.request.urlopen("https://www.python.org/")
print(type(response))  # 查看数据类型
print("="*30)
print(response.getheaders())  # 返回响应头信息
print(response.getheader("Server"))  # 返回服务器是用什么搭建的

响应对象的类型的是: HTTPResponse类型

返回响应的内容: 响应对象.read()

查看响应状态: 响应对象.status

返回响应头信息: 响应对象.getheaders()

返回服务器是用什么搭建的: 响应对象.getheader("server")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值