2016-06-25 4 views
0

Я создаю веб-искатель, используя scrapy, который просто берет все ссылки reddit на первой странице. Когда я пытаюсь помещать его в папку json, все, что я получаю, это «[».Scrapy only output '['

Вот мой паук.

from scrapy import Spider 
from scrapy.selector import Selector 
from redditScrape.items import RedditscrapeItem 


class RedditSpider(Spider): 
    name = "redditScrape" 
    allowed_domains = ["reddit.com"] 
    start_urls = [ 
     "https://www.reddit.com/r/all" 
    ] 

    def parse(self, response): 
     titles = Selector(response).xpath('//div[@class="entry unvoted lcTagged"]/p[@class="title"]') 

     for title in titles: 
      item = RedditscrapeItem() 
      item['title'] = title.xpath('/a[@class="title may-blank loggedin srTagged imgScanned"]/text()').extract() 
      yield item 

Всякий раз, когда я запускаю запрос xpath в консоли google chrome, я получаю результат, который я искал.

enter image description here

Любая идея, почему мой скребок выход обыкновение правильно?

Это команда, я использую для выполнения:

scrapy crawl redditScrape -o items.json -t json 
+0

Куда вы видите 'title can-blank loggedin srTagged imgScanned'? Это вообще не существует, 'srTagged' даже не в источнике. Я не уверен, что вы смотрите, но это не то же самое, что я вижу в своем браузере, глядя на 'https: // www.reddit.com/r/all' –

+0

Когда я проверяю элемент на reddit.com/ r/все, что у него есть в теге класса. @PadraicCunningham – Lewis

+0

Я смотрю на это сейчас, его нигде не видно! Я вижу 'title can-blank loggedin', try'. ./a[@class="title can-blank loggedin "] '' –

ответ

1

Я не знаю точно, в чем проблема, но у меня будет идти на то, что я вижу неправильно в вашем коде.

  • Во-первых, я не знаю, что -t аргумент, но я подозреваю, что вы хотели бы заверить, что выход был JSON-файл. Вам не нужно. -o items.json достаточно. scrapy crawl redditScrape -o items.json

  • Вам не нужно указывать Selector, вы также можете сделать titles = response.xpath('//div[@class="entry unvoted lcTagged"]/p[@class="title"]'). Это не ошибка, а качество улучшения жизни.

  • Второй является теневым XPath, мягко говоря, item['title'] = title.xpath('a[@class="title may-blank loggedin srTagged imgScanned"]/text()').extract_first()

Всякий раз, когда элемент успешно выход, SCRAPY добавит его в выходной файл во время выполнения.

Редактировать.

Вы можете просто использовать этот xpath //p[@class="title"]/a/text(), чтобы получить все заголовки с первой страницы. В коде это будет выглядеть примерно так

for title in response.xpath('//p[@class="title"]/a'): 
     item = RedditscrapeItem() 
     item['title'] = title.xpath('text()').extract_first() 
     yield item 
+0

Почему вы говорите, что мой второй xpath теневой? – Lewis

+0

Когда вы ставите '/' в начале xpath, вы ищете корневой элемент, который в этом случае не существует –

+0

. Я удалил/в начале xpath. Если вы подключаете две строки вместе, она работает в консоли Chrome Chrome, но в любом случае она не работает в режиме scrapy. – Lewis

1

Этот селектор CSS получит все названия:

In [13]: response.css("a.title.may-blank::text").extract() 
Out[13]: 
[u'TIL of a millionaire who announced he would bury his Bentley for his afterlife. After lots of negative reaction, he revealed the publicity stunt about organ donations. "People bury things that are much more valuable then cars and nobody seems to care".', 
u'Dog thinks he has a bunch of friends', 
u'Sewage leak at a movie theater. Looks like black tile.', 
u'3:48 am "Hydraulic Press"', 
u'I told her it was for their protection...', 
u'Long visits to nature linked to improved mental health, study finds', 
u"Vladimir Putin Says Brexit Caused by British Politicians 'Arrogance'", 
u"World's smallest man dancing with his pet cat. 26th October 1956.", 
u'I am Sue Sullivan and Reddit saved my sauce and rub company, Hot Squeeze. Tomorrow, I\u2019m heading to Wal-Mart for my last, big pitch for distribution. Whatever happens, I wanted to say thank you for all your support and AMA! Helping me out with this AMA will be Lawrence Wu, the founder WUJU hot sauce!', 
u"Cartoons made me think dog catchers were super common, but now I'm pretty sure they don't even exist", 
u'Zarya ultimate chain kill', 
u'Shaqiri scores vs Poland to make it 1-1', 
u'Mythbusters, during their later seasons', 
u"'Why not Texit?': Texas nationalists look to the Brexit vote for inspiration", 
u'Ken M on Hitler', 
u'Skill, pure skill', 
u'My girlfriend paints things. This is a pair of Vans she is currently working on.', 
u'I made a magnet wall to display my PS4 steelbook game collection!', 
u'HuffPo in 2008: "Muslims appear to be far more concerned about perceived slights to their religion than about atrocities committed daily in its name"', 
u"It's been almost 3 years since the removal of the Rose block. Never forget.", 
u"Xherdan Shaqiri's insane bicycle kick goal vs. Poland", 
u"US Customs wants to collect social media account names at the border: 'Please enter information associated with your online presence'", 
u'How was the cameraman for Finding Dory able to hold his breath for the entire filming?', 
u'Star Guardian Urgot', 
u'I made some doorstops! (Not as lame as it sounds)'] 

Чтобы добавить элемент, код просто необходимо:

In [9]: for text in response.css("a.title.may-blank::text").extract(): 
    ...:  item['title'] = text 
    ...:  yield item