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
数据进行转码,对字典进行操作
from urllib
import parse
dict={
'name':'的舒服',
'sex':'男'
}
res
=parse
.urlencode
(dict)
print(res
)
使用获取一个地址的全部的信息
from urllib
import parse
print(parse
.urlparse
(url
))
详细
from urllib
import request
resp
=request
.urlopen
('http://www.sogou.com/')
print(resp
.read
())
print(resp
.readline
())
print(resp
.readlines
())
print(resp
.getcode
())
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')
from urllib
import parse
data
={'name':'爬虫基础','greet':'hello world','age':100}
qs
=parse
.urlencode
(data
)
print(qs
)
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
())
print(parse
.parse_qs
(qs
))
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='')
'''
转载请注明原文地址:https://tech.qufami.com/read-1871.html