urllib庫

python內置的最基本的HTTP請求庫,有以下四個模塊:

urllib.request  請求模塊

urllib.error    異常處理模塊

urllib.parse   url解析模塊

urllib.robotparser? robots.txt解析模塊

?

urllib.request請求模塊:

urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)

'''urlopen()函數'''

import urllib.request

response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))    #response.read()是bytes類型的數據,要轉碼。

import urllib.parse
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
#該提交方式是post,data參數是bytes類型的鍵值對對象
response = urllib.request.urlopen("http://httpbin.org/post",data=data) #專門提供做http測試的網站
print(response.read())

#timeout是超時響應參數

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

import socket
import urllib.error
try:
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')
#響應類型
print(type(response))

#響應頭、狀態碼
response = urllib.request.urlopen("https://www.python.org")
print(response.status) #得到響應的狀態碼
print(response.getheaders()) #得到響應的Response Headers
print(response.getheader("Server")) #根據鍵得到Response Headers中指定鍵的值


'''Request()函數:當urlopen()要傳遞headers等信息時候,就要用到Request()函數,
返回一個request對象作為urlopen()函數的一個參數。'''
import urllib.parse
url = "http://httpbin.org/post"
headers = {
# 'User-Agent':'Mozilla/4.0(compatible;MSIE 5.5;Windows NT)',
'Host':'httpbin.org'
}
dict = {
'name':'Germey'
}
data = bytes(urllib.parse.urlencode(dict),encoding='utf-8')
req = urllib.request.Request(url=url,data=data,headers=headers,method='POST')
req.add_header('User-Agent','Mozilla/4.0(compatible;MSIE 5.5;Windows NT)') #可以單獨添加header
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))


'''cookie'''
import http.cookiejar,urllib.request
cookie = http.cookiejar.MozillaCookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com")
for item in cookie:
print(item.name + "=: " + item.value)

#存儲cookie
filename = "cookieLWP.txt"
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com")
cookie.save(ignore_discard=True,ignore_expires=True)
#讀取cookie
cookie = http.cookiejar.LWPCookieJar() #怎么存就怎么取
cookie.load('cookieLWP.txt',ignore_discard=True,ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com")
print(response.read().decode('utf-8'))



urllib.error異常處理模塊:
'''異常處理'''
from urllib import error
try:
response = urllib.request.urlopen("https://www.cnblogs.com/wisir/index.html")
except error.HTTPError as e:
print(e.reason,e.code,e.headers,sep='\n')
except error.URLError as e:
print(e.reason)
else:
print("Request Successfully")

try:
response = urllib.request.urlopen("https://www.baidu.com",timeout=0.01)
except urllib.error.URLError as e:
print(e.reason)
if isinstance(e.reason,socket.timeout):
print('TIME OUT')


urllib.parse URL解析模塊:
'''urlparse'''
# urllib.parse.urlparse(urlstring,scheme="",allow_fragments=True)
from urllib.parse import urlparse
result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")
print(type(result),result)

'''urlunparse:作用與urlparse相反,是將ParseResult類型的六個參數,合成一個完整的url。'''
from urllib.parse import urlunparse
data = ['http','www.baidu.com','index.html','user','a=6','comment']
print(urlunparse(data))

'''urljoin:以第二個參數為基準,若第二個參數沒有ParseResult類型六個參數中的某一個,則用第一個參數作為補充。'''
from urllib.parse import urljoin
print(urljoin("http://www.baidu.com","FAQ.html"))
print(urljoin("http://www.baidu.com","https://www.cnblogs.com/wisir/"))

'''urlencode:字典對象轉換為get請求參數'''
from urllib.parse import urlencode
params = {
'name':'germey',
'age':22
}
base_url = "http://www.baidu.com?"
url = base_url + urlencode(params)
print(url)


python3 urllib庫官方文檔:https://docs.python.org/3/library/urllib.html








轉載于:https://www.cnblogs.com/wisir/p/9969833.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/250240.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/250240.shtml
英文地址,請注明出處:http://en.pswp.cn/news/250240.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

layer的刪除詢問框的使用

刪除是個很需要謹慎的操作 我們需要進行確認 對了刪除一般使用ajax操作 因為如果同url請求 處理 再返回 會有空白頁 1.js自帶的樣式 <button type"button" data-toggle"tooltip" title"刪除" class"btn btn-danger pull-right btn-xs&qu…

文獻筆記(八)

一、基本信息 標題&#xff1a;MySQL數據庫在自動測試系統中的應用 時間&#xff1a;2017 出版源&#xff1a;寧夏職業技術學院 領域分類&#xff1a;無線互聯科技 二、研究背景 問題定義&#xff1a;文章介紹了MySQL數據庫的特點&#xff0c;結合自動測試系統運行中的實際&…

Java --- 常用API

常用API 方法重載: 方法名相同,方法接收的參數不同 static: 修飾的類,可以直接使用類名進行調用 方法名說明public static abs(int a)返回參數的絕對值public static double ceil(double a)返回大于或等于public static double floor(double a)返回小于或等于參數的最大doubl…

9. 彈出鍵盤擋住input

1.) react 中 <input className"inp3" placeholder"密碼" type"password" onChange{this.changepassword.bind(this)} onFocus{this.FocusFN.bind(this)} value{this.state.paswword}/> FocusFN(){ setTimeout(()>{ let pannel docume…

Linux初學時的一些常用命令(4)

1. 磁盤 查看當前磁盤使用情況 df -h查看某個文件大小 du -sh 文件名 如果不輸入文件名&#xff0c;默認是當前目錄的所有文件之和&#xff0c;即當前目錄大小 2. 系統內存 free參數詳解&#xff1a;https://blog.csdn.net/loongshawn/article/details/51758116 3. CPU CPU 使用…

小程序 --- 項目小練手Ⅰ

1. 接口文檔 2. 幫助文檔 小程序開發文檔 mdn 阿里巴巴字體 iconfont 3. 項目搭建 3.1 新建小程序項目 填入自己的appid: wxdbf2b5e8c2f521a3 3.2 文件結構 一級目錄 目錄名作用styles存放公共樣式components存放組件lib存放第三方庫utils自己的幫助庫request自己的接口…

vue aixos請求json

this.axios.get(/static/json/jinxiangZhe.json).then(res>{console.log(res);}).catch( error > {console.log(error,error)}) 轉載于:https://www.cnblogs.com/SunShineM/p/9087734.html

小程序 --- Tab組件的封裝

1. Tabs組件的封裝 1.1 組件的引入 使用自定義的組件很簡單,只需在使用組件的頁面的配置文件.json文件中配置. // pages/goods_list/index.json {"usingComponents":{"Tabs": "../../components/Tabs/Tabs"} }然后再.wxml文件中使用即可 <…

爬蟲之拉勾網職位獲取

重點在于演示urllib.request.Request()請求中各項參數的 書寫格式 譬如&#xff1a; url data headers...Demo演示&#xff08;POST請求&#xff09;:import urllib.requestimport urllib.parseimport json, jsonpath, csvurl "https://www.lagou.com/jobs/positionAjax.…

小程序 --- 點擊放大功能、獲取位置信息、文字樣式省略、頁面跳轉(navigateTo)

1. 點擊放大功能的實現 需求: 點擊輪播圖中的圖片會實現放大預覽的功能。首先有輪播圖的樣式如下 <!-- pages/goods_detail/index.wxml --> <!-- 輪播圖 --> <view class"detail_swiper"><swiperautoplaycircularindicator-dots><swip…

Axure實現多用戶注冊驗證

*****多用戶登錄驗證***** 一、&#xff08;常規想法&#xff09;方法&#xff1a;工作量較大&#xff0c;做起來繁瑣 1、當用戶名和密碼相同時怎么區分兩者&#xff0c;使用冒號和括號來區分&#xff1a; eg. (admin:123456)(123456:demo)(zhang:san);由此得出前面是括號后面是…

前端插件網址

http://www.swiper.com.cn/轉載于:https://www.cnblogs.com/luchuangao/p/9088057.html

python --- opencv部分學習

1. OpenCV 1.1 opencv概念 OpenCV是一個基于BSD許可(開源)發行的跨平臺計算機視覺庫可以運行在Linux、Windows、Android和Mac OS操作系統上它輕量級而且高效 – 有一系列C函數和少量 C 類構成同時提供了 Python、Ruby、MATLAB等語言的接口實現了圖像處理和計算機視覺方面的很…

hive與hbase集成

環境: hadoop2.7.7 hive3.1.0 hbase2.0.2 1.jar包拷貝(之所以用這種方式,是因為這種方式最為穩妥,最開始用的軟連接的方式,總是卻少jar包)到hive的lib目錄下刪除所有hbase相關的jar rm -rf hbase-*.jar 接著從hbase的lib目錄下拷貝所有的hbase相關jar cp -a hbasehome/lib/hba…

Winform(C#)輸入完畢后,按Enter鍵觸發Button事件

如在輸入“用戶名”和“密碼”之后&#xff0c;有些人習慣按“回車鍵”來代替頁面上的“確定”按鈕&#xff0c;那么這一功能在Winform(C#)里如何實現呢&#xff1f; 觸發密碼文本框的KeyDown事件&#xff0c;代碼如下&#xff1a; [c-sharp] view plaincopy private void txtP…

Maximum Xor Secondary(單調棧好題)

Maximum Xor Secondary CodeForces - 280B Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1,?x2,?...,?xk (k?>?1) is such maximum element xj, that the following inequa…

python --- udp的使用

1. python的模塊導入規則 參考 1.1 系統自帶模塊 系統自帶的模塊直接import導入 import time import unittest1.2 第三方下載模塊 第三方下載模塊也可以直接導入 import HTMLTestRunner import requests1.3 導入模塊的部分函數或類 from time import sleep,strftime fro…

雜項-公司:唯品會

ylbtech-雜項-公司&#xff1a;唯品會唯品會公司成立于2008年08月&#xff0c;2012年3月23日登陸美國紐約證券交易所上市&#xff08;股票代碼&#xff1a;VIPS&#xff09;。成為華南第一家在美國紐交所上市的電子商務企業。主營B2C商城唯品會名牌折扣網站是一家致力于打造中高…

python --- 使用socket創建tcp服務

1. 網絡-tcp 參考 1.1 tcp簡介 介紹 TCP協議,傳輸控制協議(英語: Transmission Control Protocol, 縮寫為TCP)是一種面向連接的、可靠的、基于字節流的傳輸層通信協議,由IETF的RFC 793定義. TCP通信需要經過創建連接、數據傳送、終止連接三個步驟. TCP通信模型中,在通信開…

Linux基本的操作

一、為什么我們要學習Linux 相信大部分人的PC端都是用Windows系統的&#xff0c;那我們為什么要學習Linux這個操作系統呢&#xff1f;&#xff1f;&#xff1f;Windows圖形化界面做得這么好&#xff0c;日常基本使用的話&#xff0c;學習成本幾乎為零。 而Linux不一樣&#xff…