客户端如果要与服务器端进行通信,需要通过http请求进行,http请求有很多种,主要的有post和get两种请求方式。比如登录、搜索某些信息的时候回用到。
#get请求--实现百度信息自动搜索
import urllib.request,re
keywd="薛怀"
keywd=urllib.request.quote(keywd)
#page=(num-1)*10
for i in range(1,11):
url="http://www.baidu.com/s?wd="+keywd+"&pn="+str((i-1)*10)
data=urllib.request.urlopen(url).read().decode("utf-8")
pat="title:'(.*?)',"
pat2='"title":"(.*?)",'
rst1=re.compile(pat).findall(data)
rst2=re.compile(pat2).findall(data)
for j in range(0,len(rst1)):
print(rst1[j])
for z in range(0,len(rst2)):
print(rst2[z])
# post请求
import urllib.request
import urllib.parse
posturl="http://www.iqianyue.com/mypost/"
postdata=urllib.parse.urlencode({
"name":"ceo@txk7.com",
"pass":"kjsahgjkashg",
}).encode("utf-8")
#进行post,就需要使用urllib.request下面的Request(真实post地址,Post数据)
req=urllib.request.Request(posturl,postdata)
rst=urllib.request.urlopen(req).read().decode("utf-8")
fh=open("E:/python/python爬虫/post.html","w")
fh.write(rst)
fh.close()
网友评论