Застрял, соскабливая несколько доменов последовательно - Python Scrapy - PullRequest
0 голосов
/ 26 сентября 2019

Я довольно новичок в python, а также в поиске в Интернете.Мой первый проект - это поиск в Интернете случайных городов Craiglist (всего 5 городов) в поддомене транспорта (т. Е. https://dallas.craigslist.org),), хотя я застрял при необходимости вручную запускать сценарий для каждого города после ручного обновления каждого соответствующего домена в соответствии с доменом.константы >>>> (start_urls = и absolute_next_url =) в сценарии. В любом случае можно ли настроить сценарий так, чтобы он последовательно проходил через определенные мной города (например, Майами, Нью-Йорк, Хьюстон, Чикаго и т. д.) и автоматически-заполнить константы для соответствующего города (start_urls = и absolute_next_url =)?

Кроме того, есть ли способ настроить скрипт для вывода каждого города в свой собственный .csv >> (т.е. miami.csv, houston.csv, chicago.csv и т. д.)?

Заранее спасибо

# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request

class JobsSpider(scrapy.Spider):
    name = "jobs"
    allowed_domains = ["craigslist.org"]
    start_urls = ['https://dallas.craigslist.org/d/transportation/search/trp']

    def parse(self, response):
        jobs = response.xpath('//p[@class="result-info"]')

        for job in jobs:
            listing_title = job.xpath('a/text()').extract_first()
            city = job.xpath('span[@class="result-meta"]/span[@class="result-hood"]/text()').extract_first("")[2:-1]
            job_posting_date = job.xpath('time/@datetime').extract_first()
            job_posting_url = job.xpath('a/@href').extract_first()
            data_id = job.xpath('a/@data-id').extract_first()


            yield Request(job_posting_url, callback=self.parse_page, meta={'job_posting_url': job_posting_url, 'listing_title': listing_title, 'city':city, 'job_posting_date':job_posting_date, 'data_id':data_id})

        relative_next_url = response.xpath('//a[@class="button next"]/@href').extract_first()
        absolute_next_url = "https://dallas.craigslist.org" + relative_next_url

        yield Request(absolute_next_url, callback=self.parse)

    def parse_page(self, response):
        job_posting_url = response.meta.get('job_posting_url')
        listing_title = response.meta.get('listing_title')
        city = response.meta.get('city')
        job_posting_date = response.meta.get('job_posting_date')
        data_id = response.meta.get('data_id')

        description = "".join(line for line in response.xpath('//*[@id="postingbody"]/text()').extract()).strip()

        compensation = response.xpath('//p[@class="attrgroup"]/span[1]/b/text()').extract_first()
        employment_type = response.xpath('//p[@class="attrgroup"]/span[2]/b/text()').extract_first()
        latitude = response.xpath('//div/@data-latitude').extract_first()
        longitude = response.xpath('//div/@data-longitude').extract_first()
        posting_id = response.xpath('//p[@class="postinginfo"]/text()').extract()


        #yield{'job_posting_url': job_posting_url, 'listing_title': listing_title, 'city':city, 'job_posting_date':job_posting_date, 'description':description, #'compensation':compensation, 'employment_type':employment_type, 'posting_id':posting_id, 'longitude':longitude, 'latitude':latitude }

        yield{'job_posting_url':job_posting_url,
                      'data_id':data_id,
                'listing_title':listing_title,
                         'city':city,
                  'description':description,
                 'compensation':compensation,
              'employment_type':employment_type,
                     'latitude':latitude,
                    'longitude':longitude,
             'job_posting_date':job_posting_date,
                   'posting_id':posting_id,
                      'data_id':data_id
              }

1 Ответ

0 голосов
/ 26 сентября 2019

Возможно, есть более понятный способ, но посмотрите https://docs.scrapy.org/en/latest/topics/practices.html?highlight=multiple%20spiders, и вы можете объединить несколько экземпляров своего паука вместе, чтобы у вас был отдельный «класс» для каждого города.Возможно, есть несколько способов консолидировать некоторый код, чтобы он не повторялся.

Что касается записи в csv, вы делаете это через командную строку прямо сейчас?Я бы добавил код к самому пауку https://realpython.com/python-csv/

...