Python Urllib庫詳解

Urllib庫詳解

什么是Urllib?

Python內置的HTTP請求庫

urllib.request 請求模塊
urllib.error 異常處理模塊
urllib.parse url解析模塊
urllib.robotparser robots.txt解析模塊

相比Python2變化

python2

import urllib2
response = urllib2.urlopen('http://www.baidu.com')

python3

import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')

urllib

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'))
import urllib.parse
import urllib.requestdata = 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')

響應

響應類型

import urllib.request
response = urllib.request.urlopen('https://www.python.org')
print(type(response))

狀態碼、響應頭

import urllib.request
response = urllib.request.urlopen('http://www.python.org')
print(response.status)
print(response.getheaders())

Request

import urllib.request
request = urllib.request.Request('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
from urllib import request,parse
url = 'http://httpbin.org/post'
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36','Host':'httpbin.org'
}
dict = {'name':'puqunzhu'
}
data = bytes(parse.urlencode(dict),encoding='utf8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
from urllib import request,parse
url = 'http://httpbin.org/post'
dict = {'name':'puqunzhu'
}
data = bytes(parse.urlencode(dict),encoding='utf8')
req = request.Request(url=url,data=data,method='POST')
req.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

Handler

代理

import urllib.request
proxy_handler = urllib.request.ProxyHandler({'http':'http://61.135.217.7:80','https':'https://61.150.96.27:46111',
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())
import http.cookiejar,urllib.request
cookie = http.cookiejar.CookieJar()
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)
import http.cookiejar,urllib.request
filename = "cookie.txt"
cookie = http.cookiejar.MozillaCookieJar(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)
import http.cookiejar,urllib.request
filename = "cookie.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)
import http.cookiejar,urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.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'))

異常處理

from urllib import request,error
try:response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:print(e.reason)
from urllib import request,error
try:response = request.urlopen('http://cuiqingcai.com/index.htm')
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")
import socket
import urllib.request
import urllib.error
try:response = urllib.request.urlopen('http://www.baiduc.com',timeout=0.01)
except urllib.error.URLError as e:print(type(e.reason))if isinstance(e.reason,socket.timeout):print("TIME OUT")

URL解析

urlparse

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

utlunoarse

from urllib.parse import urlunparse
data =['http','www.baidu.com','index.html','user','a=6','comment']
print(urlunparse(data))

urljoin

from urllib.parse import urljoin
print(urljoin('http://www.baidu.com','?category=2#comment'))
print(urljoin('htttp://www.baidu.com/about.html','htttp://www.baidu.com/FAQ.html'))

urlencode

from urllib.parse import urlencode
params = {'name':'puqunzhu','age':23
}
base_url="http://www.baidu.com?"
url=base_url + urlencode(params)
print(url)

轉載于:https://www.cnblogs.com/puqunzhu/p/9803769.html

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

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

相關文章

LVDS通信接口詳細介紹

1. 概述 LVDS Low-Voltage Differential Signaling 低電壓差分信號,屬于平衡傳輸信號。 這種技術的核心是采用極低的電壓擺幅高速差動傳輸數據,從而有以下特點: 低功耗---低誤碼率---低串擾---低抖動---低輻射 良好的信號完整性。 推…

ThinkPHP簡單的驗證碼實現

ThinkPHP簡單的驗證碼實現 寫一個最簡單的TP驗證碼。 寫Controller 首先在Controller/IndexController.class.php&#xff08;簡稱Index&#xff09;文件中編輯&#xff1a; 1 <?php 2 namespace Home\Controller; 3 use Think\Controller; 4 use Think\Verify;//這個類…

Celery框架簡單實例

Python 中可以使用Celery框架 Celery框架是提供異步任務處理的框架&#xff0c;有兩種用法&#xff0c;一種&#xff1a;應用程式發布任務消息&#xff0c;后臺Worker監聽執行&#xff0c;好處在于不影響應用程序繼續執行。第二種&#xff0c;設置定時執行&#xff08;這邊沒測…

沸騰新十年 | 中國語音產業江湖和科大訊飛的前半生

沸騰新十年 | 中國語音產業江湖和科大訊飛的前半生 2019-01-09 來源:左林右貍 寫在前面&#xff1a; 這是《沸騰新十年》的第十一篇劇透文&#xff0c;也是2019年的第一篇劇透文&#xff0c;從確認選題到采編到反復修改&#xff0c;這篇稿子操作時間前后歷經近半年。究其原…

權值

【概述】 在數學領域&#xff0c;權值指加權平均數中的每個數的頻數&#xff0c;也稱為權數或權重。在搜索引擎中&#xff0c;權值越高的內容在排序中越靠前。 實際應用中可以通過修改權值來重新調整索引在列表中的排序位置。 【示例】 1 /**2 * 創建索引3 */4 …

vue.js devtools的安裝

http://www.cnblogs.com/lolDragon/p/6268345.html http://blog.csdn.net/wxl1555/article/details/76091614 轉載于:https://www.cnblogs.com/songmengyao/p/7609548.html

[oracle]分區表學習

&#xff08;一&#xff09;什么是分區 所謂分區&#xff0c;就是將一張巨型表或巨型索引分成若干個獨立的組成部分進行存儲和管理&#xff0c;每一個相對小的&#xff0c;可獨立管理的部分&#xff0c;稱為分區。 &#xff08;二&#xff09;分區的優勢 提高數據可管理性。對表…

主函數和子函數的傳值傳址例子

#include<string.h> #include<stdlib.h> #include<stdio.h> typedef unsigned char Uint8; void *Test_Function(Uint8 **add)//返回堆空間&#xff0c;需要用二級指針 { Uint8 *devInit(Uint8 *)malloc(20*sizeof(Uint8)); memcpy(devInit,"malloc …

Matcher類的簡單使用

今天工作時遇到一個問題&#xff0c; 用正則處理html標簽時不知該如何下手。還好有Matcher幫助解決了問題。需求如下&#xff1a;例如有如下html文章內容&#xff1a;<p><a href"www.baidu.com">百度的鏈接</a>; 這是一個百度的鏈接。 <a href&…

USB 攝像頭成熟方案介紹

UVC&#xff0c;全稱為&#xff1a;USB video class 或USB video device class。是Microsoft與另外幾家設備廠商聯合推出的為USB視頻捕獲設備定義 的協議標準&#xff0c;目前已成為USB org標準之一。 如今的主流操作系統(如Windows XP SP2 and later, Linux 2.4.6 and later…

JS練習:商品的左右選擇

代碼&#xff1a; <!DOCTYPE html> <html> <head><meta charset"UTF-8"><title>商品的左右選擇</title><!--步驟分析1. 確定事件: 點擊事件 :onclick事件2. 事件要觸發函數 selectOne3. selectOne要做一些操作(將左邊選中的元…

java生成首字母拼音簡碼的總結

百度找到了某論壇高人寫的java&#xff08;具體論壇記不清了&#xff09;&#xff0c;直接用來調用&#xff0c;再次非常感謝&#xff0c;基本上實現了我的需求 package MD5;import java.util.Scanner;public class ChineseToPinYin { /** * 漢字轉拼音縮寫 * * param str * 要…

sockaddr_in , sockaddr , in_addr區別Socket編程函數集(非常有用)

一、sockaddr和sockaddr_in在字節長度上都為16個BYTE&#xff0c;可以進行轉換 struct sockaddr { unsigned short sa_family; //2 char sa_data[14]; //14 }; 上面是通用的socket地址&#xff0c;具體到Int…

Python 購物車

購物車需求&#xff1a; 可購買的商品信息顯示 顯示購物車內的商品信息、數量 購物車內的商品數量進行增加、減少 用戶余額的充值 用戶購買完成進行結賬&#xff0c;將最終余額回寫到用戶文件中   流程圖&#xff1a; 代碼&#xff1a; 1、主文件 def login():# 驗證用戶帳號…

認對畫對MOS管

MOS管我們在設計電路中經常用的一種無源器件。 首先介紹下&#xff0c;在原理圖和PCB以及實物PCBA中如何辨別各種MOS管&#xff0c;作為應用好的先決條件&#xff0c;必須認對畫對管子。 1. MOS管的GSD三極在原理圖和PCB上怎么判定&#xff1a; G極(gate)—柵極&#xff0c;原…

Jmeter之BeanShell

在Jmeter中各種分類組件中都有相應的BeanShell組件&#xff0c;這里簡單的說明一下Beanshell的使用。 一、概念 BeanShell是一種符合Java語法的腳本語言&#xff0c;也有自己的一些特定語法 二、內置變量 Jmeter在它的Beanshell中內置了變量&#xff0c;用戶可以通過這些變量與…

HDU 1875 暢通工程再續

傳送門&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid1875 簡單的最小生成樹 #include <iostream> #include <cstdio> #include <cmath> using namespace std;const int maxn100005; const double INF1.0e20;struct Node{double x,y; } isl[maxn];…

C語言變長數組 struct中char data[0]的用法

摘要&#xff1a;在實際的編程中&#xff0c;我們經常需要使用變長數組&#xff0c;但是C語言并不支持變長的數組。此時&#xff0c;我們可以使用結構體的方法實現C語言變長數組。 struct MyData {int nLen;char data[0];}; 在結構中&#xff0c;data是一個數組名&#xff1b;但…

MOS管的實際應用

繼上一篇“認對畫對MOS管”后&#xff0c;現在小結一下MOS管的具體應用&#xff1a; 應用MOS管前&#xff0c;理解MOS管每個參數的具體意義后&#xff0c;再額外注意一下管子本身的體二極管&#xff0c;本身Vf1.6V&#xff0c;導通后管子本身阻抗一般是mΩ級&#xff1b;管子廠…

imp導入前對當前用戶清庫腳本

--清空當前用戶所有表begin for i in ( select drop table || a.tab_name as sqls from (select distinct t.tab_name from (select Lower(table_name) as tab_name from user_tables) t) a ) loop dbms_output.put_line(i.sqls); execute immediate i.sqls; end loop;end;/--清…