初次学习urllib的使用

urllib.request模块

  1. 版本
    python2:urllib2、urllib
    python3:把urllib和urllib2合并,urllib.request
  2. 常用方法
    • urllib.request.urlopen(“网址”) 作用:向网站发起一个请求并获取响应
    • 字节流 = response.read()
    • 字符串 = response.read().decode(“utf-8”)
    • urllib.request.Request(“网址”,headers=“字典”),urlopen()不支持重构

==urllib.request.urlopen()==的使用

import urllib.request
# response是响应对象
response = urllib.request.urlopen('https://qq.yh31.com/zjbq/2920180.html')

# read()把响应对象里面的内容读取出来
print(response.read())

==urllib/request.Request()==的使用

import urllib.request

url = 'https://www.baidu.com/'

headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
}

# 1.创建请求对象
req = urllib.request.Request(url,headers=headers)

# 2.获取响应对象
response = urllib.request.urlopen(req)

# 3.读取响应对象内容 (read().decode('utf-8'))
html = response.read().decode('utf-8')

print(html)

# print(response.getcode()) # 返回状态码
# print(response.geturl()) # 返回实际给我们数据的URL

urllib.parse

常用方法
- urlencode(字典)
- quote(字符串)

==urllib.parse.urlencode()==的使用

# https://www.baidu.com/s?wd=%E4%B9%98%E9%A3%8E%E7%A0%B4%E6%B5%AA%E7%9A%84%E5%A7%90%E5%A7%90%E4%BB%AC&ie=utf-8

import urllib.parse

name = {'wd':'乘风破浪的姐姐'}

name = urllib.parse.urlencode(name)

print(name)

==urllib.parse.quote()==的使用

import urllib.parse

baseurl = 'https://www.baidu.com/s?wd='
name = input('请输入搜索内容:')
name = urllib.parse.quote(name)
url = baseurl + name

print(url)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值