2016-12-27 2 views
0

私はいくつかのpythonコードをscrapyで書いて、ウェブサイトからいくつかのアドレスを抽出しました。python scrapyコードは、私が読んでいるファイルを出力します

コードの最初の部分は、start_urlsの一部を形成する別のファイルgooglecoords.txtから緯度と経度の座標を読み取って、start_urlsをまとめています。 (私が以前に準備したgooglecoords.txtファイルは、googleマップで英国の郵便番号をGoogleの座標に変換します)。

ので、例えば、start_urlリストの最初の項目は、 "https://www.howdens.com/process/searchLocationsNear.php?lat=53.674434&lon=-1.4908923&distance=1000&units=MILES" どこで "LAT = 53.674434 & LON = -1.4908923" googlecoors.txtファイルから来ています。

しかし、コードを実行すると、最初にgooglecoords.txtファイルが出力される点を除いて完全に機能します。これは必要ありません。

この印刷の実行を停止するにはどうすればよいですか? (けれども私はそれと一緒に暮らすことができます。)コメントに誰かが指摘のように

import scrapy 
import sys 

from scrapy.http import FormRequest, Request 
from Howdens.items import HowdensItem 

class howdensSpider(scrapy.Spider): 
    name = "howdens" 
    allowed_domains = ["www.howdens.com"] 

    # read the file that has a list of google coordinates that are converted from postcodes 
    with open("googlecoords.txt") as f: 
     googlecoords = [x.strip('\n') for x in f.readlines()] 

    # from the goole coordinates build the start URLs 
    start_urls = [] 
    for a in range(len(googlecoords)): 
     start_urls.append("https://www.howdens.com/process/searchLocationsNear.php?{}&distance=1000&units=MILES".format(googlecoords[a])) 

    # cycle through 6 of the first relevant items returned in the text 
    def parse(self, response): 
     for sel in response.xpath('/html/body'): 
      for i in range(0,6): 
       try: 
        item = HowdensItem() 
        item['name'] =sel.xpath('.//text()').re(r'(?<="name":")(.*?)(?=","street")')[i] 
        item['street'] =sel.xpath('.//text()').re(r'(?<="street":")(.*?)(?=","town")')[i] 
        item['town'] = sel.xpath('.//text()').re(r'(?<="town":")(.*?)(?=","pc")')[i] 
        item['pc'] = sel.xpath('.//text()').re(r'(?<="pc":")(.*?)(?=","state")')[i] 
        yield item 
       except IndexError: 
        pass 
+1

データはJSONです...使用jsonパーサがそれを扱う... –

答えて

1

はあなたがstart_requests()方法でjsonモジュールでそれをロードする必要があります。

import scrapy 
import json 

class MySpider(scrapy.Spider): 
    start_urls = ['https://www.howdens.com/process/searchLocationsNear.php?lat=53.674434&lon=-1.4908923&distance=1000&units=MILES'] 

    def parse(self, response): 
     data = json.loads(response.body_as_unicode()) 
     items = data['response']['depots'] 
     for item in items: 
      url_template = "https://www.howdens.com/process/searchLocationsNear.php?{}&distance=1000&units=MILES" 
      url = url_template.format(item['lat']) # format in your location here 
      yield scrapy.Request(url, self.parse_item) 

    def parse_item(self, response): 
     print(response.url) 
関連する問題