首页 > 编程语言 > 详细

python爬虫:urllib库的简单使用

时间:2021-05-03 22:15:01      阅读:30      评论:0      收藏:0      [点我收藏+]

 

1 import urllib.request
2 #获取一个get请求
3 response = urllib.request.urlopen("http://www.baidu.com")

打开网页并返回网页内容给response
print(response.read().decode(‘utf-8‘)) #对获取到的网页进行utf-8解码

 

 

用于测试HTTP/HTTPS请求的网站

技术分享图片

 

 

 

1 #获取一个post请求
2 
3 import urllib.parse
4 data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
5 response = urllib.request.urlopen("http://httpbin.org/post",data= data)
6 print(response.read().decode("utf-8"))

 

 

#获取一个get请求
 import urllib.parse
 response = urllib.request.urlopen("http://httpbin.org/get")
 print(response.read().decode("utf-8"))

 

 

 

 

如果访问超时,或者对方网页不予返回信息,(防止程序卡死)应该如何处理。

#超时处理
try:
     response = urllib.request.urlopen("http://httpbin.org/get", timeout=10)
print(response.read().decode("utf-8")) #对网页信息进行utf-8解码
except urllib.error.URLError as e:
print("time out!")

 

 

简单解析网页信息

response = urllib.request.urlopen("http://www.baidu.com")
print(response.status) #查看状态信息(200/404/500/418)
print(response.getheaders())#查看Response Headers中的信息 
print(response.getheader("Server"))#查看Response Headers中的Server属性值(查看单一属性值)

 

 

将爬虫伪装成浏览器,以避免被网站识破,返回418信息。

 

python爬虫:urllib库的简单使用

原文:https://www.cnblogs.com/liweikuan/p/14728200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!