美文网首页
【Toki从零学Python爬虫】爬取github的代码(1)

【Toki从零学Python爬虫】爬取github的代码(1)

作者: TokiHunter | 来源:发表于2017-12-31 22:14 被阅读107次

    目录

    配置环境
    爬取github的代码(1)


    前言

    常言道,代码就在那里,不管你下载还是不下载,不离不弃。不过我单纯是闲的无聊不知道爬什么。

    定位仓库名标签

    要想爬仓库,首先要有仓库的名字。

    首先,我们来到Facebook的github主页,然后打开开发者工具。如果你常用的浏览器没有这个功能,可以尝试一下chrome。

    点击右侧箭头指向的那个按钮,然后浏览器会进入一个标签选择模式,接下来选择代表仓库名的那个标签,就是左边箭头指向的那个超链接

    <a>text</a>
    

    左键点击要选择的标签后,右侧对应的html代码会高亮。找到了要爬的内容,接下来就可以为所欲为了。

    确定仓库名的css路径

    右键点击高亮的html代码,复制 selector。
    由于我想要使用css的方式,所以需要这个内容,具体原理我并不清楚,先用着,以后再深究。


    复制到的selector是这样一串东西,大概就是一个标签.标签的css格式的路径
    #org-repositories > div.col-8.d-inline-block > div > li:nth-child(1) > div.d-inline-block.mb-1 > h3 > a
    

    我从后面截取尽量短而且有代表性的一段,这样能保证识别出来的标签是我想要的,不多不少。

    div.d-inline-block.mb-1 > h3 > a
    

    有了这个东西我们就可以过滤response,来拿到我们想要的信息了

    解析response

    首先,发起网络请求,去获取前端渲染出来的网页文件

    import scrapy
    
    class GitHubSpider(scrapy.Spider):
        name = 'githubspider'
    
        def parse(self, response):
    

    然后,用我们上一步得到的css路径,在parse中解析response。

    import scrapy
    
    class GitHubSpider(scrapy.Spider):
        name = 'githubspider'
    
        def parse(self, response):
            for text in response.selector.css('div.d-inline-block.mb-1 > h3 > a ::text').extract():
            print text
    

    很好,我们已经得到了仓库的名字,虽然只有第一页的。但是对于第一个实践项目已经足够了。

    执行下载

    有了仓库名,剩下的就是把字符串拼接起来然后执行下载,so easy!

    import scrapy
    
    import re
    import os
    
    global domain, pathList, urls
    
    domain = 'github.com'
    pathList = ['google', 'facebook']
    urls = []
    
    for path in pathList:
        urls += ['http://'+domain+'/'+path+'/']
    
    class GitHubSpider(scrapy.Spider):
        name = 'githubspider'
    
        start_urls = urls
    
        def parse(self, response):
            print '----------------------------------\n'+response.url+'\n----------------------------------'
    
            for text in response.selector.css('div.d-inline-block.mb-1 > h3 > a ::text').extract():
                projectName = re.sub(' ', '', re.sub('\n', '', text))
                
                url = ''
                for path in pathList:
                    if path in response.url :
                        url = 'git@'+domain+':'+path+'/'+projectName+'.git'
    
                print '-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n'+url
                # os.system('git clone '+url)
                print '-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-'
    

    相关文章

      网友评论

          本文标题:【Toki从零学Python爬虫】爬取github的代码(1)

          本文链接:https://www.haomeiwen.com/subject/jyiagxtx.html