【Class 44】【实例】《Python编程快速上手》 查缺补漏九 第十一章 Web之 webbrowser 和 requests

webbrowser		:是 Python 自带的,打开浏览器获取指定页面
requests		:从因特网上下载文件和网页
Beautiful Soup	:解析 HTML,即网页编写的格式
selenium		:启动并控制一个 Web 浏览器。selenium 能够填写表单,并模拟鼠标在这个浏览器中点击。

1. webbrowser 模块 启动系统默认浏览器

webbrowser 模块的 open()函数可以启动一个新浏览器,打开指定的 URL。

>>> import webbrowser
>>> webbrowser.open("http://www.baidu.com")
True
>>> webbrowser.open("www.baidu.com")
True

实例1: 实现自动打开浏览器搜索 高德地图 地址

#! python3
# -*- coding: utf-8 -*-
# 实现自动打开浏览器搜索 地图
# 如果传入参数则搜索参数地址,否则搜索鼠标剪贴板中的地址

import webbrowser, sys, pyperclip

#https://www.amap.com/search?query=徐汇区

if( len(sys.argv) > 1 ):
    # 获得命令行中传入的地址
    address = ''.join(sys.argv[1:])

else:
    # 如果没有传入参数,则从鼠标剪贴板中获取地址
    address = pyperclip.paste()

# 打开浏览器
print("https://www.amap.com/search?query="+address)
webbrowser.open("https://www.amap.com/search?query="+address)

运行实例如下:
# 鼠标剪贴板中复制 徐汇区 漕宝路 188号
PS C:\Users\Administrator\Desktop\tmp> python .\mapIt.py
https://www.amap.com/search?query=徐汇区 漕宝路 188号
PS C:\Users\Administrator\Desktop\tmp> python .\mapIt.py 徐汇区 漕宝路 188号
https://www.amap.com/search?query=徐汇区 漕宝路 188号
PS C:\Users\Administrator\Desktop\tmp> python .\mapIt.py 漕宝路 188号
https://www.amap.com/search?query=漕宝路 188号
PS C:\Users\Administrator\Desktop\tmp> python .\mapIt.py 桂林公园
https://www.amap.com/search?query=桂林公园
PS C:\Users\Administrator\Desktop\tmp>

在这里插入图片描述

2. requests 模块从网上下载文件

requests 模块让你很容易从 Web 下载文件,不必担心一些复杂的问题,诸如网络错误、连接问题和数据压缩。requests 模块不是 Python 自带的,所以必须先安装

下载安装 requests 模块
C:\Users\Administrator>pip install requests
Collecting requests
  Downloading https://files.pythonhosted.org/packages/7d/e3/20f3d364d6c8e5d2353c72a67778eb189176f08e873c9900e10c0287b84b/requests-2.21.0-py2.py3-none-any.whl (57kB)
    70% |██████████████████████▌         | 40kB 40kB/s eta 0:0    
    88% |████████████████████████████    | 51kB 40kB/s et    
    100% |████████████████████████████ ████| 61kB 47kB/s
Collecting urllib3<1.25,>=1.21.1 (from requests)
  Downloading https://files.pythonhosted.org/packages/62/00/ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/urllib3-1.24.1-py2.py3-none-any.whl (118kB)
    60% |███████████████████▌            | 71kB 17kB/s eta 0:00:0    
    69% |██████████████████████          | 81kB 19kB/s eta 0:00    
    78% |█████████████████████████       | 92kB 14kB/s eta 0    
    86% |████████████████████████████    | 102kB 13kB/s e    
    95% |██████████████████████████████▌ | 112kB 13kB/    
    100% |███████████████████ █████████████| 122kB 13kB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB)
    61% |███████████████████▌            | 81kB 23kB/s eta 0:00:0    
    69% |██████████████████████          | 92kB 24kB/s eta 0:00    
    76% |████████████████████████▌       | 102kB 26kB/s eta     
    84% |███████████████████████████     | 112kB 27kB/s et    
    92% |█████████████████████████████▌  | 122kB 29kB/s    
    99% |████████████████████████████████| 133kB 26kB    
    100% |████████████████████████████████| 143kB 34kB/s
Collecting certifi>=2017.4.17 (from requests)
  Downloading https://files.pythonhosted.org/packages/9f/e0/accfc1b56b57e9750eba272e24c4dddeac86852c2bebd1236674d7887e8a/certifi-2018.11.29-py2.py3-none-any.whl (154kB)
    59% |███████████████████             | 92kB 17kB/s eta 0:00:04    
    66% |█████████████████████           | 102kB 17kB/s eta 0:00    
    73% |███████████████████████▌        | 112kB 22kB/s eta 0    
    79% |█████████████████████████▌      | 122kB 24kB/s eta    
    86% |███████████████████████████▌    | 133kB 21kB/s e    
    92% |██████████████████████████████  | 143kB 27kB/s    
    99% |████████████████████████████████| 153kB 33kB    
    100% |████████████████████████████████| 163kB 32kB/s
Collecting idna<2.9,>=2.5 (from requests)
  Downloading https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl (58kB)
    100% |████████████████████████████████| 61kB 14kB/s
Installing collected packages: urllib3, chardet, certifi, idna, requests
Successfully installed certifi-2018.11.29 chardet-3.0.4 idna-2.8 requests-2.21.0 urllib3-1.24.1

C:\Users\Administrator>

2.1 用 requests.get()函数下载一个网页

#! python3
# -*- coding: utf-8 -*-

import requests

res = requests.get("http://www.baidu.com")
print(type(res))
print(res.text)
fp = open('baidu.html','w',encoding='utf-8')
fp.write(res.text)
fp.close()

2.2 检查错误

#! python3
# -*- coding: utf-8 -*-

import requests

try:
    res = requests.get("http://www.ssadfadbaidu.com")  # 访问一个不存在的页面,会报错
    res.raise_for_status()
    
except Exception as exc:
    print('There was a problem: %s' % (exc))
   
运行 结果如下:
PS C:\Users\Administrator\Desktop\tmp> python .\mapIt.1.py
There was a problem: HTTPConnectionPool(host='www.ssadfadbaidu.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000023298B38128>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

2.3 将下载的文件保存到硬盘

iter_content()方法在循环的每次迭代中,返回一段内容。每一段都是 bytes 数据类型,你需要指定一段包含多少字节。10 万字节通常是不错的选择,所以将 100000作为参数传递给 iter_content()。

>>> import requests
>>> res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
>>> res.raise_for_status()
>>> playFile = open('RomeoAndJuliet.txt', 'wb')
>>> for chunk in res.iter_content(100000):
 playFile.write(chunk)
100000
78981
>>> playFile.close()

猜你喜欢

转载自blog.csdn.net/Ciellee/article/details/88369620