Python爬虫从入门到懵逼-0
来源:互联网 发布:c语言基础的内容及要求 编辑:程序博客网 时间:2024/06/18 12:26
初识Python2.7 urllib库
1.实现简单网页爬取,并将网页HTML写到本地磁盘
- 首先,爬取百度首页(http://www.baidu.com)将内容读取出来付给一个变量
- 以写入的方式打开一个本地文件,命名为*.html格式
-关闭该文件
*read() 读取文件的全部内容
readline()读取文件的一行
readlines()将读到的内容赋给一个列表变量*
#--coding:utf-8--import urllib2url='http://www.baidu.com'file = urllib2.urlopen(url)data = file.read()out_put_stream = open("D:\\img\\crawlers/baidu_homepage.html", 'wb')out_put_stream.write(data)out_put_stream.close()
Python3可以用ulrlib.request.utlretrieve(url,path)直接实现不过要记得urlcleanup()清楚urlretrieve()的缓存
上述代码中file可以调用 info() getcode() geturl()得到相应信息
当爬取的网页URL中包含中文字符的时候需要进行编码处理在Python2中用urllib2.quote()进行编码 ,urllib2.unquote()解码
2.模拟浏览器访问
有些网站做了反爬处理 禁止爬虫访问 这时需要模拟浏览器进行爬取
模拟浏览器的方法是设置Headers中的User-Agent属性
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3141.7 Safari/537.36
具体实现:
- 用build_opener()修改报头
由于urlopen()不支持HTTP的高级功能 所以需要修改报头
#--coding:utf-8--import urllib2url="http://blog.csdn.net/weiwei_pig/article/details/51178226"headers=('User-Agent',"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3141.7 Safari/537.36")opener=urllib2.build_opener()#注意这里opener给add_handler赋值的方式 一个列表 不是函数调用opener.add_handler=[headers]infomation=opener.open(url).read()print infomation
- Python3.x中可以用urllib.request.Request(url).add_header(‘User-Agent’,”xx”) 注意这里add_header()是函数调用
3.设置超时时间
有时候服务器响应很慢,可以设置超时时间,超过超时时间还没有响应就判断为网页无法打开
具体实现: urlopen(url,timeout=1) timeout的单位是秒
#--coding:utf-8--import urllib2ileageURL= urllib2.quote("http://yum.iqianyue.com")print ileageURLsinaURL= urllib2.unquote(ileageURL)for i in range(1,100): try: file = urllib2.urlopen(sinaURL,timeout=1) data = file.read() print len(data) except Exception as e: print ("出现异常--"+str(e))
14165
14165
14165
14165
出现异常 urlopen error timed out
14165
阅读全文
0 0
- Python爬虫从入门到懵逼-0
- Python爬虫从入门到懵逼-1
- python爬虫从入门到精通全套
- Python爬虫从敲门到入门
- Python爬虫从入门到死亡(一)-什么是爬虫
- python爬虫入门到懵逼-2
- Python爬虫 | Python爬虫入门
- python爬虫入门简单爬虫
- Python爬虫从0开始的记录
- Python爬虫入门
- Python爬虫入门
- Python爬虫入门基础
- 如何入门 Python 爬虫?
- python 爬虫入门
- 如何入门 Python 爬虫?
- Python 爬虫入门《上》
- Python 爬虫入门《中》
- Python爬虫入门 《下》
- POJ3469: Dual Core CPU 题解
- hdu 2512 第二类斯特林数
- PHP 回调函数理解
- 两个可以快速以当前路径为根目录建立服务的工具
- HDU
- Python爬虫从入门到懵逼-0
- docker使用
- Flask-Bootstrap安装失败问题解决
- Cannot find module 'stylus'
- 卷积神经网络(CNN)前向传播算法
- (python)百练1019:Number Sequence
- 浏览器兼容性问题
- 一、30day- 新浪微博(框架)
- 卷积神经网络(CNN)反向传播算法