Scrapy CSV неправильно отформатирован - PullRequest
0 голосов
/ 09 марта 2020

Я новичок в пакете для лечения, и вот моя проблема:

import scrapy

class simpleSpider(scrapy.Spider):
    name = "simple_spider"

    start_urls = ['http://quotes.toscrape.com/login']


    def parse(self, response):
        token = response.css("input[name=csrf_token] ::attr(value)").extract_first()
        formdata = {
            'csrf_token' : token,
            'username' : 'rseiji',
            'password' : 'seiji1234'
        }

        yield scrapy.FormRequest(response.url, formdata=formdata, callback=self.parse_logged)

    def parse_logged(self, response):

        yield {
            'text' : response.css('span.text::Text').extract(),
            'author' : response.css('small.author::Text').extract(),
            'tags' : response.css('div.tags a.tag::Text').extract()
        }

Это мой паук. И это работает. Но когда я пытаюсь:

scrapy crawl simple_spider -o mySpider.csv

, файл .csv считается неправильно отформатированным. Он извлекает только текстовый столбец.

Что не так?

Спасибо!

Отредактировано: Это мой файл .csv:

text,author,tags
"“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”,“It is our choices, Harry, that show what we truly are, far more than our abilities.”,“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”,“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”,“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”,“Try not to become a man of success. Rather become a man of value.”,“It is better to be hated for what you are than to be loved for what you are not.”,“I have not failed. I've just found 10,000 ways that won't work.”,“A woman is like a tea bag; you never know how strong it is until it's in hot water.”,“A day without sunshine is like, you know, night.”","Albert Einstein,J.K. Rowling,Albert Einstein,Jane Austen,Marilyn Monroe,Albert Einstein,André Gide,Thomas A. Edison,Eleanor Roosevelt,Steve Martin","change,deep-thoughts,thinking,world,abilities,choices,inspirational,life,live,miracle,miracles,aliteracy,books,classic,humor,be-yourself,inspirational,adulthood,success,value,life,love,edison,failure,inspirational,paraphrased,misattributed-eleanor-roosevelt,humor,obvious,simile"
...

Теперь выясните, что здесь нет пустых столбцов. Формат файла .csv не очень хорошо определен. Все встало в один ряд!

1 Ответ

1 голос
/ 09 марта 2020

Решено!

import scrapy

class simpleSpider(scrapy.Spider):
    name = "simple_spider"

    start_urls = ['http://quotes.toscrape.com/login']


    def parse(self, response):
        formdata = {
            'username' : 'rseiji',
            'password' : 'seiji1234'
        }

        yield scrapy.FormRequest.from_response(response, formdata=formdata, callback=self.parse_logged,)


    def parse_logged(self, response):
        # Get list of Selector objects and loop through them
        for quote in response.css('div.quote'):
            # yield each item individually
            yield {
                'text' : quote.css('span.text::Text').extract_first(),
                'author' : quote.css('small.author::Text').extract_first(),
                'author_goodreads_url' : quote.css('span a[href*="goodreads.com"]::attr(href)').extract_first(),
                'tags' : quote.css('div.tags a.tag::Text').extract()
            }

Проблема была в том, что я использовал extract (). Я хотел получить список объектов Selector .

Использование extract () всегда приведет к выводу списка. Когда вы используете extract, вы получаете список строк html, которые вы запрашивали с помощью селектора, или при использовании extract_first () одной строки. Не используя extract () и extract_first (), вы создаете список селекторов, которые затем можете перебирать и связывать с ним новый селектор, позволяя выбирать каждый отдельный элемент.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...