日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python Urllib库详解

發(fā)布時間:2023/12/10 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python Urllib库详解 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Urllib庫詳解

什么是Urllib?

Python內(nèi)置的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))

狀態(tài)碼、響應頭

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)

轉(zhuǎn)載于:https://www.cnblogs.com/puqunzhu/p/9803769.html

總結(jié)

以上是生活随笔為你收集整理的Python Urllib库详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。