2017-01-30 157 views
1

我想使用scrapy抓取數據。但在編輯代碼時遇到困難。下面是我作爲一個實驗來完成:使用Scrapy抓取數據

import scrapy 

class BlogSpider(scrapy.Spider): 
    name = 'blogspider' 
    start_urls = ['http://anon.example.com/'] 

    def parse(self, response): 
     for title in response.css('h2'): 
      yield {'Agent-name': title.css('a ::text').extract_first()} 

     next_page = response.css('li.col-md-3 ln-t > div.cs-team team-grid > figure > a ::attr(href)').extract_first() 
     if next_page: 
      yield scrapy.Request(response.urljoin(next_page), callback=self.parse) 

我已經從網站scrapy.org使用的示例,並嘗試對其進行修改。該代碼正在做的是從給定頁面中提取所有代理的名稱。
但我希望scrapy應該進入代理頁面並從那裏提取其信息。
例如說:

Name: name of the agent 
Phone: Phone Number 
Email: email address 
website: URL of website .. etc 

希望這澄清了我的問題。我想爲這個問題提供解決方案。

回答

1
import scrapy 

class BlogSpider(scrapy.Spider): 
    name = 'blogspider' 
    start_urls = ['http://anon.example.com'] 


    # get 502 url of name 
    def parse(self, response): 
     info_urls = response.xpath('//div[@class="text"]//a/@href').extract() 
     for info_url in info_urls: 
      yield scrapy.Request(url=info_url, callback=self.parse_inof) 
    # visit each url and get info 
    def parse_inof(self, response): 
     info = {} 
     info['name'] = response.xpath('//h2/text()').extract_first() 
     info['phone'] = response.xpath('//text()[contains(.,"Phone:")]').extract_first() 
     info['email'] = response.xpath('//*[@class="cs-user-info"]/li[1]/text()').extract_first() 
     info['website'] = response.xpath('//*[@class="cs-user-info"]/li[2]/a/text()').extract_first() 
     print(info) 

name可以在詳細頁中找到,所以第一步,我們只是收集所有的詳細網址。

然後我們訪問所有的網址並獲取所有信息。

日期可能需要清理,但想法很明確。

+0

是否可以將它寫入csv文件? –

+0

@Jaffer Wilson將print打印到'yield info'並使用命令行'scrapy crawl spider_name -o out.csv'。 '-o'表示輸出文件。請閱讀scrapy文檔以獲取詳細信息。 –

+1

謝謝你的回答。但是,你能告訴我你是如何定義刮擦深度的嗎?正如我所看到的網站頁面的網址,該程序只是滾動的網址,而不是去網站。這很好。你能解釋我嗎? –