程序员

python爬虫系列-1

2018-04-02  本文已影响0人  攻城大师master

python爬虫当前主要使用的库

1.builtwith

主要用来查看构建网站使用了哪些技术
安装方法

pip install builtwith
>>> import builtwith
>>> builtwith.parse('http://www.github.com')
{u'web-frameworks': [u'Twitter Bootstrap']}

2.urllib2

想要爬取网页,需要先下载网页的内容,urllib2就是用来抓取网页内容的.

>>> urllib2.urlopen("http://www.kuaidi100.com/query?type=quanfengkuaidi&postid=390011492112").read()
'{"message":"\xe5\xbf\xab\xe9\x80\x92\xe5\x85\xac\xe5\x8f\xb8\xe5\x8f\x82\xe6\x95\xb0\xe5\xbc\x82\xe5\xb8\xb8\xef\xbc\x9a\xe5\x8d\x95\xe5\x8f\xb7\xe4\xb8\x8d\xe5\xad\x98\xe5\x9c\xa8\xe6\x88\x96\xe8\x80\x85\xe5\xb7\xb2\xe7\xbb\x8f\xe8\xbf\x87\xe6\x9c\x9f","nu":"","ischeck":"0","condition":"","com":"","status":"201","state":"0","data":[]}'

3.第一个python网络爬虫

下面这10几行代码已经是一个简单的网络爬虫.

def Download(url, retrynum=2):
    """抓取网页, retrynum=[500,600)错误重试次数"""
    print 'Downloading:', url
    try:
        html = urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print 'Download error:', e.reason
        html = None
        if retrynum > 0:
            if hasattr(e, 'code') and 500 <= e.code < 600:
                html = Download(url, retrynum-1)
    return html

Download("http://www.baidu.com")

4.总结

这个是一个爬虫的系列文章,这篇文章只是一个最简单的爬虫的代码,我们会采取由浅到深的这个一个方式来写这个系列,希望大家多多关注.github源代码

最后

上一篇 下一篇

猜你喜欢

热点阅读