python的urllib网络请求

tech2022-08-08  135

python的urllib网络请求

打开一个网址,并读取其中的内容保存内容到本地数据进行转码,对字典进行操作使用获取一个地址的全部的信息详细

打开一个网址,并读取其中的内容

from urllib import request url='http://www.baidu.com' head={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36' } req=request.Request(url=url,headers=head) resp=request.urlopen(req) print(bytes.decode(resp.read())) #读取数据 for line in resp.readlines(): print(bytes.decode(line)) #获取返回码 print(resp.getcode())

保存内容到本地

from urllib import request #request.urlretrieve(url,'one.html')

数据进行转码,对字典进行操作

from urllib import parse dict={ 'name':'的舒服', 'sex':'男' } res=parse.urlencode(dict) print(res)

使用获取一个地址的全部的信息

from urllib import parse print(parse.urlparse(url))

详细

#使用urllib的使用 from urllib import request #打开一个网址 resp=request.urlopen('http://www.sogou.com/') #读取网页的内容 print(resp.read()) print(resp.readline()) print(resp.readlines()) print(resp.getcode()) #urlretreve函数 #这个函数可以方便的将网页上的一个文件保存到本地。 #request.urlretrieve(请求地址,文件名) from urllib import request request.urlretrieve('http://www.baidu.com/','one.html') #保存图片 request.urlretrieve('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1598806101607&di=ec33fa1ecb174e01708bd0f4f8f3012f&imgtype=0&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farchive%2Fb31e377d70c6ea749fd388626e316be87c904a20.jpg','石原里美.jpg') #urlencode函数-->必须要操作字典 #urlcode可以把字典数据转化为Url编码的数据 from urllib import parse data={'name':'爬虫基础','greet':'hello world','age':100} qs=parse.urlencode(data) print(qs) #name=%E7%88%AC%E8%99%AB%E5%9F%BA%E7%A1%80&greet=hello+world&age=100 from urllib import request from urllib import parse url='https://www.baidu.com/s?ie=utf-8&' wdic={'wd':"石原里美"} url=url+parse.urlencode(wdic) print(url) rsep=request.urlopen(url) print('运行结果',resp.read()) #使用的解码parse.parse_qs(qs) print(parse.parse_qs(qs)) #{'name': ['爬虫基础'], 'greet': ['hello world'], 'age': ['100']} #分析url.parase是有params的属性的而urlsplit没有这个属性 from urllib import parse print(parse.urlparse('https://www.baidu.com/s?ie=utf-8&wd=%E7%9F%B3%E5%8E%9F%E9%87%8C%E7%BE%8E')) ''' ParseResult(scheme='https', netloc='www.baidu.com', path='/s', params='', query='ie=utf-8&wd=%E7%9F%B3%E5%8E%9F%E9%87%8C%E7%BE%8E', fragment='') '''
最新回复(0)