Skip to content
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cfp_crawler/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Basic Usage

scrapy crawl crawler
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add some documentation for the project ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, will do it

2,947 changes: 2,947 additions & 0 deletions cfp_crawler/logs.log

Large diffs are not rendered by default.

Empty file.
Binary file added cfp_crawler/proposal/__init__.pyc
Binary file not shown.
14 changes: 14 additions & 0 deletions cfp_crawler/proposal/items.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class ProposalItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Niveshkrishna, You are not declaring any item in items.py. Why?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless there are multiple crawlers which are using the same item, there's not much of difference in using the items and normal variables. Since there is only one crawler, it is okay to have them declared directly in crawler.py file. Or is it not? Is there any advantage of using items in this case?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right. But it would help to reuse a bunch of code in future and to keep everything tidy, clean and understandable.

pass
103 changes: 103 additions & 0 deletions cfp_crawler/proposal/middlewares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals


class ProposalSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.

@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s

def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.

# Should return None or raise an exception.
return None

def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.

# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i

def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.

# Should return either None or an iterable of Response, dict
# or Item objects.
pass

def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.

# Must return only requests (not items).
for r in start_requests:
yield r

def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)


class ProposalDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.

@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s

def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.

# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None

def process_response(self, request, response, spider):
# Called with the response returned from the downloader.

# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response

def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.

# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass

def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
11 changes: 11 additions & 0 deletions cfp_crawler/proposal/pipelines.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class ProposalPipeline(object):
def process_item(self, item, spider):
return item
90 changes: 90 additions & 0 deletions cfp_crawler/proposal/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*-

# Scrapy settings for proposal project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'proposal'

SPIDER_MODULES = ['proposal.spiders']
NEWSPIDER_MODULE = 'proposal.spiders'
LOG_FILE = "logs.log"

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'proposal (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we have so many comments?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is added by default by scrapy

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aaqaishtyaq please review this PR as you are also working with scrapy these days.

#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'proposal.middlewares.ProposalSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'proposal.middlewares.ProposalDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'proposal.pipelines.ProposalPipeline': 300,
#}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
Binary file added cfp_crawler/proposal/settings.pyc
Binary file not shown.
4 changes: 4 additions & 0 deletions cfp_crawler/proposal/spiders/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
Binary file added cfp_crawler/proposal/spiders/__init__.pyc
Binary file not shown.
64 changes: 64 additions & 0 deletions cfp_crawler/proposal/spiders/crawler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
import scrapy
import json
from scrapy import signals

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be 2 empty lines after import statements.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, that can be done


class CrawlerSpider(scrapy.Spider):
name = 'crawler'
Copy link

@aaqaishtyaq aaqaishtyaq Jul 22, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also can you change the name of the spider, something like cfpcrawler or cfp.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you confirm about this @ananyo2012 ?

allowed_domains = ['in.pycon.org']
url = "https://in.pycon.org"
proposals = []
file = open("proposals.json", "w")
Copy link
Contributor

@ananyo2012 ananyo2012 Jul 22, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file is opened but never closed. You should close the file after use. The best way to do this would be to use with. Something like

with open("filename.json", "w") as f:
  f.write("data")

Move it inside the spider_closed method and if you want you make the filename as a member.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops! forgot to close it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

def start_requests(self):
yield scrapy.Request(self.url + "/cfp/2018/proposals", callback = self.parse)

def parse(self, response):
proposal_links = response.xpath("//h3[@class='proposal--title']/a/@href").extract()
for link in proposal_links:
yield scrapy.Request(self.url + link, callback = self.parseProposal)



def parseProposal(self, response):
title = response.xpath("//h1[@class='proposal-title']/text()").extract()[0].strip()
author = response.xpath("//p[@class='text-muted']/small/b/text()").extract()[0].strip()
created_on = response.xpath("//p[@class='text-muted']/small/b/time/text()").extract()[0].strip()

section = response.xpath("//section[@class='col-sm-8 proposal-writeup']/div")
some_dic = {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename this to proposal . hard to understand what is some_dic .

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

for div in section:
heading = div.xpath(".//h4[@class='heading']/b/text()").extract()[0]
data = self.format_data(div.xpath(".//text()").extract(), heading)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Which data is this ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok got it. This is the main proposal content. How about we name the variables as

heading => section_heading
data => section_content

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also just being curious does div.xpath() return 2 values in a tuple ? Since I see format_data() takes in 2 arguments.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which div.xpath() are you referring to?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Niveshkrishna NVM I got it. div.xpath(".//text()").extract() is the first argument and heading is second. Rename the variable name as I suggested. Also to be more clear make a separate variable for div.xpath(".//text()").extract() say raw_section_content

data = data[2:-2]
some_dic[heading[:-1]] = data

table = response.xpath("//table/tr")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be table_rows

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

for col in table:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this should be for row in table_rows

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

heading = col.xpath(".//td/small/text()").extract()[0].strip()
data = col.xpath(".//td/text()").extract()[0].strip()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about we name these variables as

heading => extra_info_heading
data => extra_info_content

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

some_dic[heading[:-1]] = data

some_dic["title"] = title
some_dic["link_to_proposal"] = response.request.url
some_dic["author"] = author
some_dic["created_on"] = created_on
some_dic["Last Updated"] = response.xpath("//time/text()").extract()[0]

self.proposals.append(some_dic)

def format_data(self, data, head):
return " ".join([d.strip() for d in data if d != "" and d!=head ])

@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super(CrawlerSpider, cls).from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.spider_closed, signals.spider_closed)
return spider

def spider_closed(self, spider):
print("Closing spider")
json.dump(self.proposals, self.file, indent = 2, sort_keys = True)
Copy link

@aaqaishtyaq aaqaishtyaq Jul 22, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a common practice to use pipelines to save scrapy items to a file.
Something like in pipelines.py,

class JsonWritePipeline(object):

    def open_spider(self, spider):
        self.file = open('proposal.json', 'w')

    def close_spider(self, spider):
        self.file.close()

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + "\n"
        self.file.write(line)
        return item

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, could have used middlewears.py as well. But since this being not so complicated to crawl, I just hardcoded everywhere.

Copy link

@aaqaishtyaq aaqaishtyaq Jul 22, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's always a possibility of extension of any project, don't hardcode anything unless that's the only way out.

cc: @realslimshanky

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, will keep in mind




Binary file added cfp_crawler/proposal/spiders/crawler.pyc
Binary file not shown.
Loading