python 小爬虫的各种总结(一)

python真是一门非常优秀的语言,非常适合初学者,也非常适合写一些原型程序。这篇文章总结了下以前做的各种和网络相关的东西:自动登录、提取信息、模拟点击、模拟上传、取号等等,多亏了python才使世界变得那么美好!

  本次我们主要是模拟浏览器下载网页,学会了下载网页其他的下载图片什么的都是一样的套路。先上代码:

#-*-coding:utf-8-*-
'''
Created on 2014-3-4

@author: KL
'''
import urllib2
import pyquery
import sys
import pyquery
reload(sys)
sys.setdefaultencoding('utf-8')
headers = {  
    'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  
}  
def getContent(file,url,startPage,endPage):
    try:
        file.write('************************************************  ')
        file.write(str(startPage))
        file.write('  ***************************************************************
')
        for x in xrange(startPage,endPage+1):                        
            myUrl = url + str(x)            
            req = urllib2.Request(url=myUrl,headers=headers)
            myHtml = pyquery.PyQuery(urllib2.urlopen(req).read())
            for y in myHtml('div').next():
                div = pyquery.PyQuery(y)
                if div.attr('title') == None:
                    continue
                file.write('
')
                file.write(div.attr('title'))
                file.write('
')
                file.write(div(".content").text())
                file.write('
')
            file.write('
')
            file.write('
')
            file.write('
')
            file.write('************************************************  ')
            file.write(str(x+1))
            file.write('  ***********************************************************************
')
    except urllib2.HTTPError,e:
        print "error occured "+e.reason
    except urllib2.URLError,e:
        print "error occured "+e.reason
if __name__ == '__main__':
    if len(sys.argv) < 2:  
        print 'Too less argvs'  
        sys.exit()  
    searchUrl = "http://www.qiushibaike.com/hot/page/"
    file = open("qiubai.txt",'w')
    getContent(file,searchUrl,int(sys.argv[1]),int(sys.argv[2]))
    print "done"         
            
            
            

  其实主干代码就两句话(代码中的红色标出的),主要工作集中在html文档的解析过程,这里用的pquery是jquery的python移植,后面的文章会推荐更加强大的beautiful soup 真的是很Beautiful!(解析的这些都是第三方库,用起来很上手,你也可以自己用正则表达式去匹配)。

  上面这一段代码主要是抓取糗百上面的热门事件,效果如下:

原文地址:https://www.cnblogs.com/pasion-forever/p/3975789.html