pyquery response.body检索div元素

时间:2017-11-25 13:27:27

标签: python python-3.x scrapy web-crawler pyquery

我正在尝试使用scrapy和PyQuery编写一个Web爬虫。完整的蜘蛛代码如下。

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)

网页骨架

<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>

抓取工具的输出,抓取工具抓取请求网址并命中正确的网络目标,但是parse_item或parse方法没有获得响应。 Response.URL不打印。我尝试通过运行蜘蛛没有日志scrapy crawl rsscrach - nolog验证这一点,但没有打印为日志。这个问题很精细。

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)

如何获取属性的客户端,位置和大小?

1 个答案:

答案 0 :(得分:1)

我使用Scrapy制作独立脚本,测试不同的方法来获取数据,它可以正常工作。也许它可以帮助你找到问题。

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()