GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.runoob.com — Python urllib | 菜鸟教程
Python 3 教程
Python3 教程
Python3 简介
Python3 环境搭建
Python3 Pycharm
Python3 VScode
Python3 基础语法
Python3 基本数据类型
Python3 数据类型转换
Python3 解释器
Python3 注释
Python3 运算符
Python3 数字(Number)
Python3 字符串
Python3 列表
Python3 元组
Python3 字典
Python3 集合
Python3 条件控制
Python3 循环语句
Python3 编程第一步
Python3 推导式
Python3 迭代器与生成器
Python3 with
Python3 函数
Python3 lambda
Python3 装饰器
Python3 数据结构
Python3 模块
Python __name__
Python3 输入和输出
Python3 File
Python3 OS
Python3 错误和异常
Python3 面向对象
Python3 命名空间/作用域
Python 虚拟环境的创建
Python 类型注解
Python3 标准库概览
Python3 实例
Python 测验
Python3 高级教程Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQtPython urllibPython urllib 库用于操作网页 URL,并对网页的内容进行抓取处理。 本文主要介绍 Python3 的 urllib。 urllib 包 包含以下几个模块:
urllib.requesturllib.request 定义了一些打开 URL 的函数和类,包含授权验证、重定向、浏览器 cookies等。 urllib.request 可以模拟浏览器的一个请求发起过程。 我们可以使用 urllib.request 的 urlopen 方法来打开一个 URL,语法格式如下: urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
实例如下: 实例
from urllib.request import urlopen myURL = urlopen("https://www.runoob.com/") print(myURL.read()) 以上代码使用 urlopen 打开一个 URL,然后使用 read() 函数获取网页的 HTML 实体代码。 read() 是读取整个网页内容,我们可以指定读取的长度: 实例
from urllib.request import urlopen myURL = urlopen("https://www.runoob.com/") print(myURL.read(300)) 除了 read() 函数外,还包含以下两个读取网页内容的函数:
我们在对网页进行抓取时,经常需要判断网页是否可以正常访问,这里我们就可以使用 getcode() 函数获取网页状态码,返回 200 说明网页正常,返回 404 说明网页不存在: 实例
import urllib.request myURL1 = urllib.request.urlopen("https://www.runoob.com/") print(myURL1.getcode()) # 200 try: myURL2 = urllib.request.urlopen("https://www.runoob.com/no.html") except urllib.error.HTTPError as e: if e.code == 404: print(404) # 404 更多网页状态码可以查阅:https://www.runoob.com/http/http-status-codes.html。 如果要将抓取的网页保存到本地,可以使用 Python3 File write() 方法 函数: 实例
from urllib.request import urlopen myURL = urlopen("https://www.runoob.com/") f = open("runoob_urllib_test.html", "wb") content = myURL.read() # 读取网页内容 f.write(content) f.close() 执行以上代码,在本地就会生成一个 runoob_urllib_test.html 文件,里面包含了 https://www.runoob.com/ 网页的内容。 更多Python File 处理,可以参阅:https://www.runoob.com/python3/python3-file-methods.html 。URL 的编码与解码可以使用 urllib.request.quote() 与 urllib.request.unquote() 方法: 实例
import urllib.request encode_url = urllib.request.quote("https://www.runoob.com/") # 编码 print(encode_url) unencode_url = urllib.request.unquote(encode_url) # 解码 print(unencode_url) 输出结果为: https%3A//www.runoob.com/ https://www.runoob.com/ 模拟头部信息我们抓取网页一般需要对 headers(网页头信息)进行模拟,这时候需要使用到 urllib.request.Request 类: class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
实例 - py3_urllib_test.py 文件代码
import urllib.request import urllib.parse url = 'https://www.runoob.com/?s=' # 菜鸟教程搜索页面 keyword = 'Python 教程' key_code = urllib.request.quote(keyword) # 对请求进行编码 url_all = url+key_code header = { 'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } #头部信息 request = urllib.request.Request(url_all,headers=header) reponse = urllib.request.urlopen(request).read() fh = open("./urllib_test_runoob_search.html","wb") # 将文件写入到当前目录中 fh.write(reponse) fh.close() 执行以上 Python 代码,会在当前目录生成 urllib_test_runoob_search.html 文件,打开 urllib_test_runoob_search.html 文件(可以使用浏览器打开),内容如下:
表单 POST 传递数据,我们先创建一个表单,代码如下,我这里使用了 PHP 代码来获取表单的数据: 实例 - py3_urllib_test.php 文件代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com) urllib POST 测试</title> </head> <body> <form action="" method="post" name="myForm"> Name: <input type="text" name="name"><br> Tag: <input type="text" name="tag"><br> <input type="submit" value="提交"> </form> <hr> <?php // 使用 PHP 来获取表单提交的数据,你可以换成其他的 if(isset($_POST['name']) && $_POST['tag'] ) { echo $_POST["name"] . ', ' . $_POST['tag']; } ?> </body> </html> 实例
import urllib.request import urllib.parse url = 'https://www.runoob.com/try/py3/py3_urllib_test.php' # 提交到表单页面 data = {'name':'RUNOOB', 'tag' : '菜鸟教程'} # 提交数据 header = { 'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } #头部信息 data = urllib.parse.urlencode(data).encode('utf8') # 对参数进行编码,解码使用 urllib.parse.urldecode request=urllib.request.Request(url, data, header) # 请求处理 reponse=urllib.request.urlopen(request).read() # 读取结果 fh = open("./urllib_test_post_runoob.html","wb") # 将文件写入到当前目录中 fh.write(reponse) fh.close() 执行以上代码,会提交表单数据到 py3_urllib_test.php 文件,输出结果写入到 urllib_test_post_runoob.html 文件。 打开 urllib_test_post_runoob.html 文件(可以使用浏览器打开),显示结果如下:
urllib.errorurllib.error 模块为 urllib.request 所引发的异常定义了异常类,基础异常类是 URLError。 urllib.error 包含了两个方法,URLError 和 HTTPError。 URLError 是 OSError 的一个子类,用于处理程序在遇到问题时会引发此异常(或其派生的异常),包含的属性 reason 为引发异常的原因。 HTTPError 是 URLError 的一个子类,用于处理特殊 HTTP 错误例如作为认证请求的时候,包含的属性 code 为 HTTP 的状态码, reason 为引发异常的原因,headers 为导致 HTTPError 的特定 HTTP 请求的 HTTP 响应头。 对不存在的网页抓取并处理异常: 实例
import urllib.request import urllib.error myURL1 = urllib.request.urlopen("https://www.runoob.com/") print(myURL1.getcode()) # 200 try: myURL2 = urllib.request.urlopen("https://www.runoob.com/no.html") except urllib.error.HTTPError as e: if e.code == 404: print(404) # 404
urllib.parseurllib.parse 用于解析 URL,格式如下: urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True) urlstring 为 字符串的 url 地址,scheme 为协议类型, allow_fragments 参数为 false,则无法识别片段标识符。相反,它们被解析为路径,参数或查询组件的一部分,并 fragment 在返回值中设置为空字符串。 实例
from urllib.parse import urlparse o = urlparse("https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B") print(o) 以上实例输出结果为: ParseResult(scheme='https', netloc='www.runoob.com', path='/', params='', query='s=python+%E6%95%99%E7%A8%8B', fragment='') 从结果可以看出,内容是一个元组,包含 6 个字符串:协议,位置,路径,参数,查询,判断。 我们可以直接读取协议内容: 实例
from urllib.parse import urlparse o = urlparse("https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B") print(o.scheme) 以上实例输出结果为: https 完整内容如下:
urllib.robotparserurllib.robotparser 用于解析 robots.txt 文件。 robots.txt(统一小写)是一种存放于网站根目录下的 robots 协议,它通常用于告诉搜索引擎对网站的抓取规则。 urllib.robotparser 提供了 RobotFileParser 类,语法如下: class urllib.robotparser.RobotFileParser(url='') 这个类提供了一些可以读取、解析 robots.txt 文件的方法:
实例
>>> import urllib.robotparser >>> rp = urllib.robotparser.RobotFileParser() >>> rp.set_url("http://www.musi-cal.com/robots.txt") >>> rp.read() >>> rrate = rp.request_rate("*") >>> rrate.requests 3 >>> rrate.seconds 20 >>> rp.crawl_delay("*") 6 >>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco") False >>> rp.can_fetch("*", "http://www.musi-cal.com/") True
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
| ||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |