Итак, я пытаюсь работать с проектом Scrapy под названием RISJbot для извлечения содержимого новостных статей для моего исследования, однако я столкнулся с проблемой, которую не могу найти источник илиспособ исправить это: паук на самом деле не возвращает тексты тела (не удалось найти ни одного в «Вашингтон пост», и немногие на CNN), что было бы очень важно в случае статьи.
IЯ не очень знаком с Python, но из того, что я понимаю, он делает несколько попыток найти текст тела, и, если он не может это сделать, он возвращает версию в кодировке gzipped и Base 64.
Что бывы рекомендуете мне делать? Пока я не мог найти способ исправить это.
Вот сам паук:
# -*- coding: utf-8 -*-
from RISJbot.spiders.newssitemapspider import NewsSitemapSpider
from RISJbot.loaders import NewsLoader
# Note: mutate_selector_del_xpath is somewhat naughty. Read its docstring.
from RISJbot.utils import mutate_selector_del_xpath
from scrapy.loader.processors import Identity, TakeFirst
from scrapy.loader.processors import Join, Compose, MapCompose
import re
class WashingtonPostSpider(NewsSitemapSpider):
name = 'washingtonpost'
# allowed_domains = ['washingtonpost.com']
# A list of XML sitemap files, or suitable robots.txt files with pointers.
sitemap_urls = ['https://www.washingtonpost.com/news-sitemaps/index.xml']
def parse_page(self, response):
"""@url http://www.washingtonpost.com/business/2019/10/25/us-deficit-hit-billion-marking-nearly-percent-increase-during-trump-era/?hpid=hp_hp-top-table-main_deficit-210pm%3Ahomepage%2Fstory-ans
@returns items 1
@scrapes bodytext bylines fetchtime firstpubtime headline source url
@noscrapes modtime
"""
s = response.selector
# Remove any content from the tree before passing it to the loader.
# There aren't native scrapy loader/selector methods for this.
#mutate_selector_del_xpath(s, '//*[@style="display:none"]')
l = NewsLoader(selector=s)
# WaPo's ISO date/time strings are invalid: <datetime>-500 instead of
# <datetime>-05:00. Note that the various standardised l.add_* methods
# will generate 'Failed to parse data' log items. We've got it properly
# here, so they aren't important.
l.add_xpath('firstpubtime',
'//*[@itemprop="datePublished" or '
'@property="datePublished"]/@content',
MapCompose(self.fix_iso_date)) # CreativeWork
# These are duplicated in the markup, so uniquise them.
l.add_xpath('bylines',
'//div[@itemprop="author-names"]/span/text()',
set)
l.add_xpath('section',
'//*[contains(@class, "headline-kicker")]//text()')
# Add a number of items of data that should be standardised across
# providers. Can override these (for TakeFirst() fields) by making
# l.add_* calls above this line, or supplement gaps by making them
# below.
l.add_fromresponse(response)
l.add_htmlmeta()
l.add_schemaorg(response)
l.add_opengraph()
l.add_scrapymeta(response)
return l.load_item()
def fix_iso_date(self, s):
return re.sub(r'^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}[+-])'
'([0-9])([0-9]{2})$',
r'\g<1>0\g<2>:\g<3>',
s)
Полное сообщение об ошибке (у него нет части "Traceback"):
ОШИБКА: RISJbot.pipelines.checkcontent: без bodytext: https://www.washingtonpost.com/world/europe/russia-and-cuba-rebuild-ties-that-frayed-after-cold-war/2019/10/29/d046cc0a-fa09-11e9-9e02-1d45cb3dfa8f_story.html
Я также обнаружил еще одну ошибку, хотя не уверен, связана ли она спроблема bodytext:
ОШИБКА: scrapy.utils.signal: Ошибка обработчика сигнала:> Трассировка (последний последний вызов): файл "C: \ Users \ sigalizer \ Anaconda3 \ envs \ scrapyenv \lib \ site-packages \ twisted \ internet \ defer.py ", строка 151, в MaybeDeferred result = f (* args, ** kw) Файл" C: \ Users \ sigalizer \ Anaconda3 \ envs \ scrapyenv \ lib \ site-packages \ pydispatch \ robustapply.py ", строка 55, в robustApply возвращает получателя (* аргументы, ** названы) Файл" C: \ Users \ sigalizer \ Anaconda3 \ envs \ scrapyenv \ lib \ site-packages \ scrapy \ extensions \ feedexport ".py ", строка 243, в item_scraped slot = self.slot AttributeError: у объекта 'FeedExporter' нет атрибута 'slot'