python爬虫基础--------urllib模块学习

1、urllib的安装

windows命令下

pip install urllib

pycharm中已经集成了,直接使用即可。

2、模块的使用

2.1、get请求。默认是get请求

#引入模块
import urllib.request

#获取一个get请求
response = urllib.request.urlopen("https://cn.bing.com/")
print(response)                             #<http.client.HTTPResponse object at 0x000001C13A1D2F98>
print(response.read().decode('utf-8'))      #对获取的网页原码进行utf-8解码

输出的则是bing的网页原码。

这里urlopen是打开一个网页,用response接收返回的信息。

2.2、post请求

import urllib.request
#获取一个post请求   http://httpbin.org/  模拟用户登陆

import urllib.parse     #解析
data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")   #字节文件封装
response = urllib.request.urlopen("http://httpbin.org/post",data= data)
print(response.read().decode('utf-8'))

其中 http://httpbin.org/  可以模拟用户登陆

运行结果:

post请求是需要传入数据的,即将data传入。

这与 http://httpbin.org/  中post方法结果相同。

2.3、异常处理

#获取一个get请求   timeout=1 超时,处理异常
try:
    response = urllib.request.urlopen("http://httpbin.org/get",timeout=0.01)
    print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
    print("timeout")

2.4、状态码

测试  http://httpbin.org/

response = urllib.request.urlopen("http://httpbin.org/get")
print(response.status)          #状态码 200

测试 http://douban.com

response = urllib.request.urlopen("http://douban.com")
print(response.status)          #状态码 418   被发现是爬虫

这里发现我们是爬虫,就返回了418。

2.5、获取headers信息

response = urllib.request.urlopen("https://cn.bing.com/")
print(response.getheaders())

这结果和网页里面的headers相同

获取其中某一个信息

response = urllib.request.urlopen("https://cn.bing.com/")
print(response.getheader("date"))   #获取其中某一个信息

2.6、伪装成浏览器

最重要的是需要user-agent的信息

查看自己浏览器的user-agent,并复制

url = "http://httpbin.org/post"
#伪装浏览器,用字典的结构包装
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36"}

data = bytes(urllib.parse.urlencode({"name":"eric"}),encoding="utf-8")
req = urllib.request.Request(url,data=data,headers=headers,method="POST")     #请求对象
response = urllib.request.urlopen(req)    #发送请求
print(response.read().decode("utf-8"))

结果如下

模拟成浏览器的信息了,这与2.2中的"User-Agent": "Python-urllib/3.6", 完全不同

最后我们来模拟浏览器,对 http://www.douban.com 进行页面获取。最重要的是user-agent

url = "http://www.douban.com"
#伪装浏览器
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36"}

req = urllib.request.Request(url,headers=headers)     #请求对象
response = urllib.request.urlopen(req)    #发送请求
print(response.read().decode("utf-8"))

运行结果

可以得到网页原码。

 

 

注意:如果要使用data信息

data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")

则需要引入:

import urllib.parse     #解析

其他的均需要引入

import urllib.request

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值