Urllib模块是python的URL处理模块。它用于获取URL(统一资源定位符)。它使用网址功能, 并能够使用各种不同的协议来获取URL。
Urllib是一个软件包, 它收集了几个用于处理URL的模块, 例如:
- urllib.request用于打开和阅读。
- urllib.parse用于解析URL
- urllib.error引发的异常
- urllib.robotparser用于解析robot.txt文件
如果你的环境中不存在urllib, 请执行以下代码进行安装。
pip install urllib 让我们详细了解这些。
urllib.request
该模块有助于定义函数和类以打开URL(主要是HTTP)。打开此类URL的最简单方法之一是:
urllib.request.urlopen(URL)
我们可以在示例中看到:
import urllib.request request_url = urllib.request.urlopen( 'https://www.srcmini05.com/' ) print (request_url.read()) The source code of the URL i.e. srcmini. urllib.parse
该模块有助于定义函数来操纵URL及其组成部分, 以构建或破坏它们。通常, 它着重于将URL分成多个小部分。或将不同的URL组件连接到URL字符串中。
我们可以从下面的代码中看到这一点:
from urllib.parse import * parse_url = urlparse( 'https://www.srcmini05.com /python-langtons-ant/' ) print (parse_url) print ( "\n" ) unparse_url = urlunparse(parse_url) print (unparse_url) ParseResult(scheme='https', netloc='www.srcmini05.com', path='/python-langtons-ant/', params='', query='', fragment='') https://www.srcmini05.com/python-langtons-ant/ 注意:-URL的不同组成部分被分开并再次结合在一起。尝试使用其他网址以更好地理解。
urllib.parse的其他不同功能是:
| 函数 | 采用 |
|---|---|
| urllib.parse.urlparse | 分隔URL的不同组成部分 |
| urllib.parse.urlunparse | 连接URL的不同组成部分 |
| urllib.parse.urlsplit | 它与urlparse()类似, 但不拆分参数 |
| urllib.parse.urlunsplit | 合并urlsplit()返回的元组元素以形成URL |
| urllib.parse.urldeflag | 如果URL包含片段, 则它将返回一个URL, 以删除该片段。 |
urllib.error
此模块定义urllib.request引发的异常类。每当获取URL时发生错误时, 此模块都会帮助引发异常。以下是引发的异常:
- URLError –引发URL错误或由于连接而获取URL时出错的错误, 并具有” reason”属性, 该属性可告知用户错误原因。
- HTTPError –对于异常的HTTP错误(例如, 身份验证请求错误)引发。它是子类或URLError。典型错误包括” 404″(找不到页面), ” 403″(禁止请求),
和” 401″(需要验证)。
我们可以在以下示例中看到这一点:
# URL Error import urllib.request import urllib.parse # trying to read the URL but with no internet connectivity try : x = urllib.request.urlopen( 'https://www.google.com' ) print (x.read()) # Catching the exception generated except Exception as e : print ( str (e)) URL Error: urlopen error [Errno 11001] getaddrinfo failed # HTTP Error import urllib.request import urllib.parse # trying to read the URL try : x = urllib.request.urlopen( 'https://www.google.com /search?q = test' ) print (x.read()) # Catching the exception generated except Exception as e : print ( str (e)) HTTP Error 403: Forbidden urllib.robotparser
该模块包含单个类RobotFileParser。此类回答有关特定用户是否可以获取发布robot.txt文件的URL的问题。
Robots.txt是网站管理员创建的文本文件, 用于指示网络机器人如何在其网站上抓取网页。
robot.txt文件告诉Web抓取器不应该访问服务器的哪些部分。
例如 :
# importing robot parser class import urllib.robotparser as rb bot = rb.RobotFileParser() # checks where the website's robot.txt file reside x = bot.set_url( 'https://www.srcmini05.com /robot.txt' ) print (x) # reads the files y = bot.read() print (y) # we can crawl the main site z = bot.can_fetch( '*' , 'https://www.srcmini05.com/' ) print (z) # but can not crawl the disallowed url w = bot.can_fetch( '*' , 'https://www.srcmini05.com /wp-admin/' ) print (w) None None True False 注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
srcmini
评论前必须登录!
注册