互联网大数据:Python实现网络爬虫(算法编程技巧)

标签:
urllib2-proxyhandler浏览器cookies正则表达式解析库验证码gzip压缩多线程并发抓取 |
分类: IT/OT/IOT:工业通讯三网融合 |
【前言】
很多资深人士都有自己的Python网络爬虫编程心得,现收集一些如下所示,供我们快速借鉴学习。
【Python爬虫常用技巧小结】
1)基本抓取网页
1.1)直接get数据
import urllib2
url
respons = urllib2.urlopen(url)
print response.read()
1.2)处理post表单
import urllib
import
urllib2
url = "http://abcde.com"
form = {'name':'abc','password':'1234'}
form_data = urllib.urlencode(form)
request = urllib2.Request(url,form_data)
response = urllib2.urlopen(request)
print response.read()
2)使用代理IP访问
专门应对IP被封掉的情况,在urllib2包中有ProxyHandler类,通过此类可以设置代理IP访问网页。
import
urllib2
proxy = urllib2.ProxyHandler({'http': '127.0.0.1:8087'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
response = urllib2.urlopen('http://www.baidu.com')
print response.read()
3)处理Cookies数据
Cookies是为了辨别用户身份、进行Session跟踪而储存在用户本地终端上的加密数据。Python提供了cookielib模块用于处理cookies,cookielib提供可存储cookie的对象,与urllib2模块配合使用来访问Internet资源。
import urllib2, cookielib
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support)
urllib2.install_opener(opener)
content = urllib2.urlopen('http://XXXX').read()
要点:CookieJar()用于管理HTTP cookie值、存储HTTP请求生成的cookie、向传出的HTTP请求添加cookie的对象。整个cookie都存储在内存中,对CookieJar实例进行垃圾回收后cookie也将丢失,所有过程都不需要单独去操作。如需手动添加cookie,则代码如下。
cookie =
"PHPSESSID=91rurfqm2329bopnosfu4fvm
request.add_header("Cookie", cookie)
4)伪装成浏览器
某些网站对爬虫一律拒绝请求。所以用urllib2直接访问网站经常会出现HTTP Error 403: Forbidden的情况。对有些 header要特别留意,Server端会针对这些 header做检查,例如:对于User-Agent有些 Server或Proxy会检查该值,用来判断是否是浏览器发起的Request;对于Content-Type在使用REST接口时,Server会检查该值,用来确定HTTP Body中的内容该怎样解析。这时可以通过修改http包中的header来实现。
import urllib2
headers = {
}
request = urllib2.Request(
)
print urllib2.urlopen(request).read()
5)页面解析
使用正则表达式解析网页,
入门:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html,
在线测试:http://tool.oschina.net/regex/ 。
关于解析库,目前常用的有两个:lxml和BeautifulSoup,都是HTML/XML的处理库。Beautifulsoup通过纯python实现,效率低,但是功能实用,比如能用通过结果搜索获得某个HTML节点的源码;而lxmlC语言编码,高效,支持Xpath。
6)验证码的处理
对于一些简单的验证码,可以进行简单的识别。对于有些非常复杂的验证码,可以通过打码平台进行人工打码。
7)gzip压缩
某些网页不论怎么转码都是一团乱码,这是因为许多web服务具有发送压缩数据的能力,可以将网络线路上传输的大量数据消减 60% 以上。这尤其适用于XML web服务,因为XML数据的压缩率可以很高。但一般服务器不会为你发送压缩数据,除非你告诉服务器你可以处理压缩数据。
import urllib2, httplib
request = urllib2.Request('http://xxxx.com')
request.add_header('Accept-encoding',
'gzip')
opener = urllib2.build_opener()
f = opener.open(request)
要点:创建Request对象,添加Accept-encoding头信息告诉服务器能接受gzip压缩数据,然后解压缩数据。
import StringIO
import
gzip
compresseddata = f.read()
compressedstream = StringIO.StringIO(compresseddata)
gzipper = gzip.GzipFile(fileobj=compressedstream)
print gzipper.read()
8)多线程并发抓取
单线程太慢的话,就需要多线程,以下是个简单的并发的线程池模板。虽然Python多线程很鸡肋,但是对于爬虫这种网络频繁型,还是能一定程度提高效率的。
from threading import Thread
from Queue import Queue
from time import sleep
#q是任务队列
#NUM是并发线程总数
#JOBS是有多少任务
q = Queue()
NUM = 2
JOBS = 10
#具体的处理函数,负责处理单个任务
def do_somthing_using(arguments):
#这个是工作进程,负责不断从队列取数据并处理
def working():
#fork NUM个线程等待队列
for i in range(NUM):
#把JOBS排入队列
for i in range(JOBS):
#等待所有JOBS完成
q.join()
【更多Python常用学习库汇总】
1)GUI 图形界面
Tkinter : https://wiki.python.org/moin/TkInter/
wxPython : https://www.wxpython.org/
PyGTK: http://www.pygtk.org/
PyQt : https://sourceforge.net/projects/pyqt/
PySide : http://wiki.qt.io/Category:LanguageBindings::PySide
2)Web框架
django:https://www.djangoproject.com/
flask:http://flask.pocoo.org/
tornadoweb :http://www.tornadoweb.org/en/stable/
webpy:http://webpy.org/
cherrypy:http://cherrypy.org/
jinjs:http://docs.jinkan.org/docs/jinja2/
3)科学计算
numpy:http://www.numpy.org/
SciPy:https://www.scipy.org/
pandas: http://pandas.pydata.org/
blaze: http://blaze.readthedocs.io/en/latest/index.html
4)密码学
cryptography:https://pypi.python.org/pypi/cryptography/
hashids:http://www.oschina.net/p/hashids
Paramiko:http://www.paramiko.org/
Passlib:https://pythonhosted.org/passlib/
PyCrypto:https://pypi.python.org/pypi/pycrypto
PyNacl:http://pynacl.readthedocs.io/en/latest/
5)爬虫相关
scrapy:https://scrapy.org/
pyspider: https://github.com/binux/pyspider
portia:https://github.com/scrapinghub/portia
html2text:https://github.com/Alir3z4/html2text
BeautifulSoup:https://www.crummy.com/software/BeautifulSoup/
lxml:http://lxml.de/
selenium:http://docs.seleniumhq.org/
mechanize:https://pypi.python.org/pypi/mechanize
PyQuery:https://pypi.python.org/pypi/pyquery/
creepy:https://pypi.python.org/pypi/creepy
6)图像处理
bigmoyan:http://scikit-image.org/
Python Imaging Library(PIL):http://www.pythonware.com/products/pil/
pillow: http://pillow.readthedocs.io/en/latest/
7)自然语言处理
nltk: http://www.nltk.org/
snownlp: https://github.com/isnowfy/snownlp
Pattern:https://github.com/clips/pattern
TextBlob:http://textblob.readthedocs.io/en/dev/
Polyglot:https://pypi.python.org/pypi/polyglot
jieba: https://github.com/fxsjy/jieba
8)数据库驱动
mysql-python: https://sourceforge.net/projects/mysql-python/
PyMySQL:https://github.com/PyMySQL/PyMySQL
PyMongo:https://docs.mongodb.com/ecosystem/drivers/python/
【END】