对于urllib中的get请求方式,可以直接传入url的连接即可访问页面,但是对于要传入关键字的话,也可以用quote进行编码再传入。
案例如下:
1 #get请求搜索参数如何添加
2 import urllib.request
3 try:
4 url="http://www.baidu.com/s?wd="
5 #注意:在urllib 中这种的headers 是需要是字典的
6 key1="python"
7 key1_url=urllib.request.quote(key1)
8 key2=" web开发"
9 key2_url=urllib.request.quote(key2)
10 all_url=url+key1_url+key2_url
11
12 req=urllib.request.Request(url=all_url)
13 file=urllib.request.urlopen(req,timeout=10)
14 html=file.read()
15 print(html)
16
17 except Exception as e:
18 print("时间超时",str(e))
可以传入关键字key="关键字",用key1_url=urllib.request.quote(key1)进行编码,最后将字符串连接起来得到all_url再进行访问即可。