2017-08-20 61 views
0

我是Python和Scrapy的新手。我想從網站http://www.vodafone.com.au/about/legal/critical-information-summary/plans中提取信息,包括文件的鏈接,名稱和有效的。使用python scrapy提取鏈接和文本

我試過這段代碼,但它不起作用。如果有人能解釋並幫助我,我將不勝感激。

這裏是文件vodafone.py

import scrapy 

from scrapy.linkextractor import LinkExtractor 
from scrapy.spiders import Rule, CrawlSpider 
from vodafone_scraper.items import VodafoneScraperItem 


class VodafoneSpider(scrapy.Spider): 
    name = 'vodafone' 
    allowed_domains = ['vodafone.com.au'] 
    start_urls = ['http://www.vodafone.com.au/about/legal/critical-information-summary/plans'] 

    def parse(self, response): 
     for sel in response.xpath('//tbody/tr/td[1]/a'): 
      item = VodafoneScraperItem() 
      item['link'] = sel.xpath('href').extract() 
      item['name'] = sel.xpath('text()').extract_first() 

      yield item 

回答

0

因爲是由JavaScript動態生成的頁面內容它不工作。您嘗試從中提取數據的元素不存在於Scrapy收到的HTML源代碼中(您可以在瀏覽器中打開頁面源代碼時看到自己)。

你有兩個選擇:

  1. 嘗試看看你會不會發現,該頁面使用任何API。在瀏覽器的開發人員工具中查找網絡選項卡上的XHR請求。幸運的是,這個具體頁面似乎從http://www.vodafone.com.au/rest/CIS?field:planCategory:equals=Mobile%20Plans&field:planFromDate:lessthaneq=20/08/2017這樣的請求中獲取數據。它返回可以解析的JSON。
  2. 另一種選擇是渲染包含JavaScript的頁面,然後解析它。我建議使用Splash,因爲它通過scrapy-splash庫與Scrapy無縫集成。
0

相反的要求:

start_urls = ['http://www.vodafone.com.au/about/legal/critical-information-summary/plans'] 

您可以設置start_urls到:

start_urls = ['http://www.vodafone.com.au/rest/CIS?field:planCategory:equals=Mobile%20Plans&field:planFromDate:lessthaneq=22/08/2017'] 

比轉換response.body以JSON格式:

response_json = json.loads(response.body) 

現在會給你網站上的所有對象。現在簡單地重複一個循環了,並得到所需的數據:

for item_json in response_json: 
    item["link"] = item_json["document"]["file"] 
    item["name"] = item_json["document"]["name"] 

完整的代碼片段是在這裏:

import scrapy 
import json 
from vodafone_scraper.items import VodafoneScraperItem 


class VodafoneSpider(scrapy.Spider): 
    name = 'vodafone' 
    allowed_domains = ['vodafone.com.au'] 
    start_urls = [ 
     'http://www.vodafone.com.au/rest/CIS?field:planCategory:equals=Mobile%20Plans&field:planFromDate:lessthaneq=22/08/2017'] 

def parse(self, response): 
    response_json = json.loads(response.body) 
    for item_json in response_json: 
     item = VodafoneScraperItem() 
     item["link"] = item_json["document"]["file"] 
     item["book"] = item_json["document"]["name"] 

     yield item