互联网访问
互联网是由无数设备组成的网络,在此之前,我们的输入输出都是发生在本机上。基于urllib
模块,我们可以使用Python访问互联网。urllib
是python内置的HTTP
请求库,无需安装即可使用,它包含了4个模块:
-
request:打开和读取 URL
-
error:包含 urllib.request 抛出的异常,如果出现错误可以捕获这些异常
-
parse:用于解析 URL,提供了许多URL处理方法,如:拆分、解析、合并等
-
robotparser:用于解析
robots.txt
文件,然后判断哪些网站可以爬
访问互联网白话的说就是访问其他计算机,并读取存储在其他计算机上的数据。HTTP
协议是计算机之间的通信协议,除此之外,还有其他各种通信协议,例如,TCP/IP
协议。
发起请求
发起一个 HTTP
请求,我们需要用到 urllib.request
模块。urllib.request
的作用不仅仅是发起请求, 还能获取请求返回结果。例如:
urllib.request.urlopen()
打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作
import urllib.request
#试一试,看下输出些啥
response=urllib.request.urlopen('https://www.python.org') #请求站点获得一个HTTPResponse对象
print(response.read().decode('utf-8')) #返回网页内容
print(response.getheader('server')) #返回响应头中的server值
print(response.getheaders()) #以列表元祖对的形式返回响应头信息
print(response.fileno()) #返回文件描述符
print(response.version) #返回版本信息
print(response.status) #返回状态码200,404代表网页未找到
print(response.debuglevel) #返回调试等级
print(response.closed) #返回对象是否关闭布尔值
print(response.geturl()) #返回检索的URL
print(response.info()) #返回网页的头信息
print(response.getcode()) #返回响应的HTTP状态码
print(response.msg) #访问成功则返回ok
print(response.reason) #返回状态信息
错误解析
假如你尝试访问著名的404网站"http://www.google.com"
,会就出现异常,作为程序,我们需要对这种异常进行处理。
import urllib.request
import urllib.error
url = "http://www.google.com"
try:
response = request.urlopen(url)
except error.URLError as e:
#找到原因,根据实际业务需求做其他处理
print(e.reason)
GET和POST请求
以上的代码都是GET
请求,HTTP
请求除了GET
请求之外,还有POST
请求也是最常用的。
GET
请求是你向服务器
发送了读数据的请求,而POST
请求是你向服务器
发送了写数据请求。
示例GET:
import urllib.request
import urllib.parse
dic = {'name':'melon','age':18}
data = urllib.parse.urlencode(dic)
req = urllib.request.urlopen('http://127.0.0.1:8000/index?%s'%data)
content = req.read()
示例POST:
import urllib.request
import urllib.parse
import json
dic = {'name':'melon','age':18}
data = urllib.parse.urlencode(dic)
req = urllib.request.Request('http://127.0.0.1:8000/index', data.encode())
opener = urllib.request.urlopen(req)
content = json.loads(opener.read().decode())
当你 urllib.urlopen
一个 https
的时候会验证一次 SSL 证书,当目标使用的是自签名的证书时就会出现一个URLError,如果是这样可以在开头加上
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
小案例
Bing必应的每日图片都是非常精美的壁纸,现在我们尝试使用Python来下载必应每日图片
。
import urllib.request
import re
import datetime
import os
bing_url = 'https://www.bing.com'
response = urllib.request.urlopen(bing_url)
html = response.read().decode('utf-8')
img_urls = re.findall('id="bgLink" rel="preload" href="(.*?)&', html, re.S)
for url in img_urls:
daily_img_url = bing_url + url
print(daily_img_url)
# 获取 年-月-日 ,图片将以 ‘2020-07-15.jpg’的形式保存
ymd = datetime.datetime.now().strftime('%Y-%m-%d')
print(ymd)
# 保存图片至程序运行的当前位置,你也可以指定其他目录
parent_path = os.path.abspath(os.path.dirname(__file__))
# 拼接出图片保存路径
img_save_path = '%s/%s.jpg' % (parent_path, ymd)
print(img_save_path)
with open(img_save_path, 'wb') as fp:
# 读取图片数据并写入
img_data = urllib.request.urlopen(daily_img_url).read()
fp.write(img_data)