栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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()解码:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/33029.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号