[python相关]python 访问网页

来源:互联网 发布:淘宝旺铺智能版装修 编辑:程序博客网 时间:2024/05/02 00:05

from:http://fsldn.blog.163.com/blog/static/45464320108284238755/

 

简单的抓取网页:
import urllib.request
url="http://google.cn/"
response=urllib.request.urlopen(url) #返回文件对象
page=response.read()

有个办法直接将URL保存为本地文件:
import urllib.request
url="http://www.xxxx.com/1.jpg"
urllib.request.urlretrieve(url,r"d:\temp\1.jpg")

网页抓取实际上分为2步:第一步是发出请求,第二步接收服务器返回的数据,在Python中也是这么做的.
POST方式:
01.import urllib.parse
02.import urllib.request
03.
04.url="http://liuxin-blog.appspot.com/messageboard/add"
05.
06.values={"content":"命令行发出网页请求测试"}
07.data=urllib.parse.urlencode(values)
08.
09.#创建请求对象
10.req=urllib.request.Request(url,data)
11.#获得服务器返回的数据
12.response=urllib.request.urlopen(req)
13.#处理数据
14.page=response.read()

GET方式:
01.import urllib.parse
02.import urllib.request
03.
04.url="http://www.google.cn/webhp"
05.
06.values={"rls":"ig"}
07.data=urllib.parse.urlencode(values)
08.
09.theurl=url+"?"+data
10.#创建请求对象
11.req=urllib.request.Request(theurl)
12.#获得服务器返回的数据
13.response=urllib.request.urlopen(req)
14.#处理数据
15.page=response.read()