python3.0
之前,通常为urllib2
、urllib
结合使用python3
把urllib
和urllib2
合并成urllib.request
urllib.request.urlopen(url)
:向url
发送请求并获取响应
response.read()
-> 得到网页内容,编码为bytesresponse.read().decode('utf-8')
可以得到以字符串为编码的网页内容import urllib.request
html = urllib.request.urlopen(
'https://818ps.com/muban/biaoqingbao.html?user_source=r416508&sdclkid=b52pALol15jpALAR&bd_vid=8269777356919846594')
print(html.read().decode('utf-8'))
urllib.request.urlopen()
不能增加这个参数,所以需要用到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.116 Safari/537.36'}
# 1、创建请求对象
html = urllib.request.Request(url, headers=headers)
# 2、响应对象
response = urllib.request.urlopen(html)
# 3、获取网页内容
print(response.read().decode('utf-8'))
read()
-> 读取服务器响应的内容getcode()
-> 返回HTTP的响应码geturl()
-> 返回实际数据的URL(防止重定向问题)urllib.parse.urlencode(参数:字典)
-> 将字符串转换成形如%E6%9F%AF%E5%8D%97
import urllib.request
import urllib.parse
# https://www.baidu.com/s?wd=%E6%9F%AF%E5%8D%97
url = 'https://www.baidu.com/s?'
name = input("请输入要搜索的内容:")
# 定义一个字典,与urllib.parse.urlencode的传参形式一致
wd = {'wd': name}
# 将汉字转成形如%E6%9F%AF%E5%8D%97
wd = urllib.parse.urlencode(wd)
# 拼接完整url
url = url + wd
headers = headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
# 创建请求对象
req = urllib.request.Request(url, headers=headers)
# 发送请求并获取响应
res = urllib.request.urlopen(req)
# 获取网页内容
html = res.read().decode('utf-8')
# 打印内容
print(html)
urllib.parse.quote(参数:字符串)
-> 将字符串转换成形如%E6%9F%AF%E5%8D%97
import urllib.parse
# https://www.baidu.com/s?wd=%E6%9F%AF%E5%8D%97
url = 'https://www.baidu.com/s?'
name = input('请输入你要搜索的内容:')
name = urllib.parse.quote(name)
# 拼接完整url
url = url + name
headers = headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
# 创建请求对象
req = urllib.request.Request(url, headers=headers)
# 发送请求并获取响应
res = urllib.request.urlopen(req)
# 获取网页内容
html = res.read().decode('utf-8')
# 打印内容
print(html)
GET 特点 :查询参数在URL地址中显示
POST
urllib.request.Request(url,data=data,headers=headers)
本文地址:https://blog.csdn.net/weixin_44604586/article/details/107269978
如对本文有疑问, 点击进行留言回复!!
Python之Pandas and Numpy 吐血整理(持续更新!!!)
网友评论