-1

I am trying to write a web crawler using scrapy and PyQuery.The full spider code is as follows.

from scrapy import Spider
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class gotspider(CrawlSpider):
        name='gotspider'
        allowed_domains=['fundrazr.com']
        start_urls = ['https://fundrazr.com/find?category=Health']
        rules = [
        Rule(LinkExtractor(allow=('/find/category=Health')), callback='parse',follow=True)
            ] 


def parse(self, response):
    self.logger.info('A response from %s just arrived!', response.url)
    print(response.body)

The web page skeleton

<div id="header">
<h2 class="title"> Township </h2>
<p><strong>Client: </strong> Township<br>
<strong>Location: </strong>Pennsylvania<br>
<strong>Size: </strong>54,000 SF</p>
 </div>

output of the crawler, The crawler fetches the Requesting URL and its hitting the correct web target but the parse_item or parse method is not getting the response. The Response.URL is not printing. I tried to verify this by running the spider without logs scrapy crawl rsscrach--nolog but nothing is printed as logs. The problem is very granular.

2017-11-26 18:07:12 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: rsscrach)
2017-11-26 18:07:12 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'rsscrach', 'NEWSPIDER_MODULE': 'rsscrach.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['rsscrach.spiders']}
2017-11-26 18:07:12 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats']
2017-11-26 18:07:12 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-11-26 18:07:12 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-11-26 18:07:12 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-11-26 18:07:12 [scrapy.core.engine] INFO: Spider opened
2017-11-26 18:07:12 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-11-26 18:07:12 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6024
2017-11-26 18:07:13 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://fundrazr.com/robots.txt> (referer: None)
2017-11-26 18:07:14 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://fundrazr.com/find?category=Health> (referer: None)
2017-11-26 18:07:15 [scrapy.core.engine] INFO: Closing spider (finished)
2017-11-26 18:07:15 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 605,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 13510,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 11, 26, 10, 7, 15, 46516),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'memusage/max': 52465664,
 'memusage/startup': 52465664,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 11, 26, 10, 7, 12, 198182)}
2017-11-26 18:07:15 [scrapy.core.engine] INFO: Spider closed (finished)

How do I get the Client, Location and Size of the attributes ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Raghu
  • 313
  • 2
  • 7
  • 19
  • do you get error message ? did you use `print()` to see what you have in variables - ie. what do you get in `response.body`. Maybe you get response without `h2` – furas Nov 25 '17 at 21:22
  • format code. now it has wrong indentions. always add tag `python` - it highlights code. – furas Nov 25 '17 at 21:22
  • BTW: `scarpy` has `css selector` which can use instead of `PyQuery` – furas Nov 25 '17 at 23:04
  • @furas I am trying to debug by adding `self.logger.info('A response from %s just arrived!', response.body)` but I am not able to see the logger info in python console as well as in the generated logs. – Raghu Nov 26 '17 at 04:28
  • use `print()` and you will see all. – furas Nov 26 '17 at 08:03
  • BTW: `Scrapy` as default sends response to `parse()`, not `parse_item()` - did you change it ? – furas Nov 26 '17 at 08:05
  • `print(response.url)`,`print(response.body)` I tried both parse() and parse_item(). I am getting the output like The request is reaching the webpage but `parse_item` or `parse` is not returning the response. - Posting the output of the scrapy spider – Raghu Nov 26 '17 at 10:12
  • what is the real url ? Maybe page uses JavaScript to add elements - and then it will not work because Scarpy doesn't run JavaScript. You will need `Selenium` to control web browser which can run JavaScript. – furas Nov 26 '17 at 10:16
  • The same page gets the response in scrappy shell `scrapy shell https://fundrazr.com/find?category=Health` the response is `In [1]: response.url Out[1]: 'https://fundrazr.com/find?category=Health'` – Raghu Nov 26 '17 at 10:18
  • I don't know, in shell it works for me too. I can't say anything without spider code. – furas Nov 26 '17 at 10:31
  • I have posted the entire spider code for your reference – Raghu Nov 26 '17 at 10:47

1 Answers1

1

I made standalone script with Scrapy which test different methods to get data and it works without problem. Maybe it helps you find your problem.

import scrapy
import pyquery

class MySpider(scrapy.Spider):

    name = 'myspider'

    start_urls = ['https://fundrazr.com/find?category=Health']

    def parse(self, response):
        print('--- css 1 ---')
        for title in response.css('h2'):
            print('>>>', title)

        print('--- css 2 ---')
        for title in response.css('h2'):
            print('>>>', title.extract()) # without _first())
            print('>>>', title.css('a').extract_first())
            print('>>>', title.css('a ::text').extract_first())
            print('-----')

        print('--- css 3 ---')
        for title in response.css('h2 a ::text'):
            print('>>>', title.extract()) # without _first())

        print('--- pyquery 1 ---')
        p = pyquery.PyQuery(response.body)
        for title in p('h2'):
            print('>>>', title, title.text, '<<<') # `title.text` gives "\n"

        print('--- pyquery 2 ---')
        p = pyquery.PyQuery(response.body)
        for title in p('h2').text():
            print('>>>', title)
        print(p('h2').text())

        print('--- pyquery 3 ---')
        p = pyquery.PyQuery(response.body)
        for title in p('h2 a'):
            print('>>>', title, title.text)

# ---------------------------------------------------------------------

from scrapy.crawler import CrawlerProcess

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})

process.crawl(MySpider)
process.start()
furas
  • 134,197
  • 12
  • 106
  • 148
  • Thanks The missing part was process.start(). in my code `process.start(stop_after_crawl=False)` avoid unnecessary port issues. One more doubt is how is pyquery objects getting traced. `

    Township Library

    Client: Township
    Location: Pennsylvania
    Size: 34,000 SF

    ` I need to grab all strong elements along with its value how to get it ?
    – Raghu Nov 26 '17 at 12:48
  • You could get all as one string `txt = p('p').text()` - `Client: Township Location: Pennsylvania Size: 54,000 SF` - and split it into list `data = txt.split(' ')` - `['Client:', 'Township', 'Location:', 'Pennsylvania', 'Size:', '54,000', 'SF']`. If you want to keep `SF` with `'54,000' as '54,000 SF` then you can use second parameter in `txt.split(' ', 5)`. But all this works only if client name and location are single words (not `New York`) . – furas Nov 26 '17 at 13:09
  • Thanks @furas I was able to get the entire data the txt has multiple words as well , for instance Client: Township one , Location : Pennsylvania,Newyork. Straight forward split(:) might not work out Need some regexp(). I am trying to split it – Raghu Nov 26 '17 at 14:12