urllib基本的使用

139 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情

使用

导入urllib对象,然后定义一个网址,使用urllib.requeset.urlopen方法打开这个网址,通过response.read方法获取返回的内容,会返回一个字节形式的二进制编码数据,然后解析成utf-8的编码

import  urllib.request
url="http://www.baidu.com"

response=urllib.request.urlopen(url)
content=response.read().decode('utf-8')
print(content)

urllib的类型和方法

上面urllib.request.urlopen的返回值的类型是<class 'http.client.HTTPResponse'>, response.read方法一个字节一个字节读取内容 response.read(555)参数代表返回多少字节 response.readline()代表读取一行 response..readlines()代表读取每一行,返回一个列表

验证是否成功 response.getcode(),如果返回200,表示请求成功 response.geturl(),获取访问的url地址 response.getheaders()获取所有的响应头

使用爬虫下崽

下载网站和和图片, 可以把网址地址改成图片地址,然后文件名改成.jpg,和文件源格式一致的后缀名

import  urllib.request
url="http://www.baidu.com"

response=urllib.request.urlretrieve(url,'xxx.html')

下载视频,,下载视频可能遇到了问题。可能会报错,因为为默认验证证书是否合法。所以要先取消证书 全局取消证书验证

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

然后使用视频链接,然后使用视频文件后缀。下载即可成功


import urllib.request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
vodeo='https://vd3.bdstatic.com/mda-mc5ed37q2tphn6pc/v1-cae/sc/mda-mc5ed37q2tphn6pc.mp4?v_from_s=hkapp-haokan-hbe&auth_key=1664898089-0-0-17715068ccd358fa1622f5b73256f1d2&bcevod_channel=searchbox_feed&pd=1&cd=0&pt=3&logid=0689807647&vid=8497652441251037491&abtest=104960_1&klogid=0689807647'
urllib.request.urlretrieve(vodeo,'xx.mp4')

访问百度就收到反爬的制裁

因为百度是要传User-Agent(简称ua);所以就不能使用简单的参数获取了。在openUrl的时候传入ua. window上可以直接这么操作

import urllib.request

headers = {
    'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"}
url = "https://www.baidu.com"
request=urllib.request.Request(url,headers=headers)
response=urllib.request.urlopen(request)
content=response.read().decode('utf-8')
print(content)

但是mac🐶日的报错。还是要关闭证书,才可以。

编码

urllib.parse.quote('实则棒')可以把文本转换为url编码格式

import urllib.request
content=urllib.parse.quote('实则棒')
print(content)