stackoverflow.py 2.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
import os
import json
import urllib.request
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
import scrapy

from scrapy.crawler import CrawlerProcess
from scrapy.settings import Settings

class StackOverflowTagSpider(scrapy.Spider):
F
feilong 已提交
12
    name = "stackoverflow_tags"
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    allowed_domains = ["visualstudio.com"]
    start_urls = ['https://stackoverflow.com/tags/synonyms?page=1']
    custom_settings = {
    	'ITEM_PIPELINES':{'tag_source.stackoverflow.TagPipeline': 301},
        'LOG_LEVEL': 'INFO'
    }

    def __init__(self):
        self.totgal_pages = 45
        self.page_count = 0

    def parse(self, response):
        self.page_count += 1
        tags = response.css('.post-tag::text')
        for tag in tags:
            yield {
                'name': tag.get()
            }
        
        if self.page_count<self.totgal_pages:
            next_page_list = response.css('a.js-pagination-item::attr(href)')
            if len(next_page_list)>0:
                next_page_item = next_page_list[len(next_page_list)-1]
                next_page = next_page_item.get()
                print('next_page:', next_page)
                yield response.follow(next_page, callback=self.parse, dont_filter=True)

class TagPipeline(object):
    def open_spider(self, spider):
        self.file = open('dataset/stackoverflow.tag.json', 'w')
        self.file.write('[\n')
        self.count = 0
F
feilong 已提交
45
        self.tags = {}
46 47 48 49 50 51

    def close_spider(self, spider):
        self.file.write('\n]')
        self.file.close()

    def process_item(self, item, spider):
F
feilong 已提交
52 53 54 55
        if self.tags.get(item['name']) is not None:
            return
        self.tags[item['name']] = True

56 57 58 59 60 61 62 63 64 65 66 67 68 69
        words = []
        if self.count>0:
            words.append(',\n')
        words.append('  ')
        words.append(json.dumps(item, ensure_ascii=False).strip())
        line = ''.join(words)
        self.file.write(line)
        self.count += 1

def fetch():
    settings = Settings()
    process = CrawlerProcess()
    process.crawl(StackOverflowTagSpider)
    process.start()