python

超轻量级php框架startmvc

python访问抓取网页常用命令总结

更新时间:2020-04-29 09:06 作者:startmvc
python访问抓取网页常用命令简单的抓取网页:importurllib.requesturl="http://google.cn/"response=urllib.req

python访问抓取网页常用命令

简单的抓取网页:


import urllib.request 
url="http://google.cn/" 
response=urllib.request.urlopen(url) #返回文件对象
page=response.read() 

直接将URL保存为本地文件:


import urllib.request 
url="http://google.cn/" 
response=urllib.request.urlopen(url) #返回文件对象
page=response.read() 

POST方式:


import urllib.parse 
import urllib.request 
 
url="http://liuxin-blog.appspot.com/messageboard/add" 
 
values={"content":"命令行发出网页请求测试"} 
data=urllib.parse.urlencode(values) 

#创建请求对象 
req=urllib.request.Request(url,data) 
#获得服务器返回的数据 
response=urllib.request.urlopen(req) 
#处理数据 
page=response.read() 

GET方式:


import urllib.parse 
import urllib.request 
 
url="http://www.google.cn/webhp" 
 
values={"rls":"ig"} 
data=urllib.parse.urlencode(values) 
 
theurl=url+"?"+data 
#创建请求对象 
req=urllib.request.Request(theurl) 
#获得服务器返回的数据 
response=urllib.request.urlopen(req) 
#处理数据 
page=response.read() 

有2个常用的方法,geturl(),info()

geturl()的设置是为了辨别是否有服务器端的网址重定向,而info()则包含了一系列的信息。

中文问题的处理,会用到 encode()编码 dencode()解码:

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!