0
点赞
收藏
分享

微信扫一扫

python网络爬虫实战教学——urllib的使用(3)

在这里插入图片描述

文章目录

专栏导读

1、urlsplit

这个方法和 urlparse 方法非常相似,只不过它不再单独解析 params 这一部分(params 会合并到path中),只返回5个结果。实例如下:

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

运行结果如下:

SplitResult(scheme='https', netloc='www.baidu.com', path='/index.html;user',
 query='id=5', fragment='comment')

可以发现,返回结果是SplitResult,这其实也是一个元组,既可以用属性名获取其值,也可以用索引获取。
实例如下:

from urllib.parse import urlsplit
result = urlsplit('https://ww.baidu.com/index.html;user?id=5#corment')
print(result.scheme,result[0])

运行结果如下:

https https

2、urlunsplit

与urlunparse方法类似,这也是将链接各个部分组合成完整链接的方法,传入的参数也是一个可迭代对象,例如列表、元组等,唯一区别是这里参数的长度必须为5。

实例如下:

from urllib.parse import urlunsplit
data =['https','waw.baidu.com','index.html','a-6','comment']
print(urlunsplit(data))

运行结果如下:

https://waw.baidu.com/index.html?a-6#comment

3、urljoin

urlunparse和urlunsplit方法都可以完成链接的合并,不过前提都是必须有特定长度的对象,链接的每一部分都要清晰分开。
除了这两种方法,还有一种生成链接的方法,是urljoin。我们可以提供一个base_url(基础链接)作为该方法的第一个参数,将新的链接作为第二个参数。urljoin方法会分析base_url的scheme、netloc和path这3个内容,并对新链接缺失的部分进行补充,最后返回结果。

下面通过几个实例看一下:

from urllib.parse import urljoin
print(urljoin('https://wnw.baidu.com','FAQ.html'))
print(urljoin('htps://wsw.baidu.com','https://cuiqingcai.com/FA0.html'))
print(urljoin('https://asw.baidu.com/about.html','https://culqingcal.com/FAQ.html'))
print(urljoin('https://wsw.baldu.com/about.html',"https://culqingcal.com/FA0.html?question-2"))
print(urljoin('https://ww.baidu.com?wd-abc','https://cuiqingcal.com/index.php'))
print(urljoin('https://.baidu.com','?category-2#comment'))
print(urljoin('wm.baidu.com',"?category-2#comment"))
print(urljoin("wn.baidu.comtcoment","category-2"))

运行结果如下:

https://wnw.baidu.com/FAQ.html
https://cuiqingcai.com/FA0.html
https://culqingcal.com/FAQ.html
https://culqingcal.com/FA0.html?question-2
https://cuiqingcal.com/index.php
https://.baidu.com?category-2#comment
wm.baidu.com?category-2#comment
category-2

可以发现,base_url提供了三项内容:scheme、netloc和path。如果新的链接里不存在这三项,就予以补充;如果存在,就使用新的链接里面的,base_url中的是不起作用的。
通过urljoin方法,我们可以轻松实现链接的解析、拼合与生成。

4、urlencode

这里我们再介绍一个常用的方法——urlencode,它在构造GET请求参数的时候非常有用.
实例如下:

from urllib.parse import urlencode
paramg = {'name':'gerney','age':25}
base_url ='https://Man.baidu.com?'
url=base_url+urlencode(paramg)
print(url)

运行结果如下:

https://Man.baidu.com?name=gerney&age=25

可以看到,参数已经成功地由字典类型转化为GET请求参数。
urlencode方法非常常用。有时为了更加方便地构造参数,我们会事先用字典将参数表示出来,然后将字典转化为URL的参数时,只需要调用该方法即可。

在这里插入图片描述

举报

相关推荐

0 条评论