urllib

urillb 崔老师爬虫系列课程学习笔记

urlopen

urllib.request.urlopen(url,data=None,[timeout,]*,cafil=None,capath=None,cadefault=False,context=None)

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
import urllib.parse
import urllib.request

data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())
import urllib.request

response = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(response.read())
import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin/get',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')

响应

响应类型

import urllib 
response = urllib.request.urlopen('http://python.org')
print(type(response))

状态码,响应头

import urllib
response = urllib.request.urlopen('http://www.python.org')
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
import urllib
response = urllib.request.urlopen('http://www.python.org')
print(response.read().decode('utf-8'))

Request

import urllib.request

request = urllib.request.Request('http://www.python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
from urllib import request,parse

url = 'http://httpbin.org/post'
headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36'
,'Host': 'httpbin.org'
}
dict = {
    'name':'Germey'
}
data = bytes(parse.urlencode(dict),encoding='utf8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

from urllib import request,parse

url = 'http://httpbin.org/post'
dict = {
    'name':'Germey'
}
data = bytes(parse.urlencode(dict),encoding='utf8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
req.add_header('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36'
)
response = request.urlopen(req)
print(response.read().decode('utf-8'))

Handler

代理

import urllib.request

proxy_handler = urllib.request.ProxyHandler({'http':'http://127.0.0.1:9743'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://httpbin.org/get')
print(response.read())
import http.cookiejar,urllib.request

cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"+"+item.value)
import http.cookiejar,urllib.request
filename = "cookie.txt"
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires=True)

import http.cookiejar,urllib.request

filename = "cookie2.txt"
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires=True)
import urllib.request,http.cookiejar
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie2.txt',ignore_discard=True,ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))

异常处理

from urllib import request,error

try:
    response = request.urlopen('http://www.cuiqingcai.com/index.htm')
except error.URLError as e:
    print(e.reason)
from urllib import request,error

try:
    response = request.urlopen('http://www.cuiqingcai.com/index.htm')
except error.HTTPError as e:
    print(e.reason,e.code,e.headers,sep='\n')
except error.URLError as e:
    print(e.reason)
else:
    print("Request Successfuly")
from urllib import request, error
import socket

try:
    response = request.urlopen('http://www.baidu.com',timeout=0.01)
except error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')

URL解析

urlparse

urllib.parse.urlparse(urlstring,scheme=”,allow_fragments=True)

from urllib.parse import urlparse

result = urlparse('www.baidu.com/index.html;user?id=5#comment',scheme='https')
print(result)
from urllib.parse import urlparse

result = urlparse('www.baidu.com/index.html;user?id=5#comment',scheme='https',allow_fragments=False)
print(result)

urlunparse

用于拼接

urljoin

from urllib.parse import urljoin

print(urljoin('http://www.baidu.com','https://cuiqingcai.com/FAQ.html'))

urlencode

from urllib.parse import urlencode

params = {
    'name':'germey',
    'age':22
}
base_url = 'http://www.baidu.com?'
url = base_url+urlencode(params)
print(url)
import urllib.request
import urllib
import re

def get_html(url):
    response = urllib.request.urlopen(url)
    html = response.read()
    return html

def get_img(html):
    reg = r'src="(.*?)"'
    pattern = re.compile(reg)
    imglist = re.findall(pattern,html)
    i = 0
    for imgurl in imglist:
        urllib.urlretrieve(imgurl,'%s.jpg'%i)
        i+=1
html = get_html('http://tieba.baidu.com/p/2166231880')
print(html)
print (get_img(html))
### 关于 `urllib` 的更新信息 #### 寻找最新版本 为了获取 `urllib` 的最新版本,需要注意的是 `urllib` 是 Python 标准库的一部分,并不是通过 pip 安装的独立包。因此,在尝试使用 pip 安装 `urllib` 时会遇到错误提示:ERROR: Could not find a version that satisfies the requirement urllib (from versions: none) ERROR: No matching distribution found for urllib[^1]。 由于 `urllib` 属于 Python 自身的标准库模块之一,其随同 Python 解释器一同分发并自动安装。要获得最新的 `urllib` 版本,则需确保所使用的 Python 解释器是最新的稳定版。例如,随着 Python 新版本(如 Python 3.9.7)的发布,其中包含了经过改进和修复后的 `urllib` 模块[^2]。 #### 获取发行说明与更新日志 有关 `urllib` 的具体变更记录以及新增特性等内容通常可以在官方文档中的“what's new”部分找到。这部分文档描述了不同版本间的差异及其带来的改动详情。对于想要深入了解某个特定功能或者解决已知问题的情况来说非常重要。可以访问 [Python 官方网站](https://docs.python.org/zh-cn/3/) 查看对应版本下的 “What’s New In Python X.Y?” 页面来获取详细的更新日志。 #### 如何升级到最新版本 既然 `urllib` 已经集成到了 Python 中,那么所谓的“升级”实际上就是指升级整个 Python 环境至更高版本的过程。如果当前环境中存在多个 Python 版本共存的需求,建议采用虚拟环境工具(比如 venv 或 conda),以便更好地管理依赖关系而不影响全局设置。当准备就绪后,可以通过下载安装程序或利用包管理系统来进行 Python 升级操作;如果是基于 Anaconda 的工作流,则可以直接执行命令 `conda update python` 来完成此过程。 ```bash # 使用 Conda 更新 Python 到最新版本 conda update python ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值