如何使用scrapy抓取Ask引擎搜索结果?

bkkx9g8r  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(121)

我创建了一个spider来从一组用户定义的关键字中抓取Ask搜索结果。但是,每当我运行命令scrapy crawl pageSearch -o test.json时,它都会为我创建一个空的test.json文件,我不知道为什么。要创建这个api,我的灵感来自于一个开发人员page,他展示了如何抓取谷歌的SERP,以及官方文档中的教程。这是我从命令line中得到的一个git。我从堆栈溢出问题中搜索了解决方案,但没有成功。我相信是从下面的命令提示符行得到的:'scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',这是一个http错误,但在互联网上搜索后,它不是,根据我的终端我的机器人运行成功,我在我的代码中指定的url地址是有效的,在那里刮发生.和个人,我没有看到我的错误,所以我迷路了.这里是我的代码:

import scrapy
import json
import datetime

class PagesearchSpider(scrapy.Spider):
    name = 'pageSearch'

    def start_requests(self):
        queries = [ 'love']
        for query in queries:
            url = 'https://www.ask.com/web?q='+query
            yield scrapy.Request(url, callback=self.parse, meta={'pos': 0})

    def parse(self, response):
           print(response.text)
           di = json.loads(response.text)
           pos = response.meta['pos']
           dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
           for result in di['organic_results']:
               title = result['a.PartialSearchResults-item-title-link.result-link']
               snippet = result['p.PartialSearchResults-item-abstract']
               link = result['div.PartialSearchResults-item-url']
               item = {'title': title, 'snippet': snippet, 'link': link, 'position': pos, 'date': dt}
               pos += 1
               yield item

               next_page = di['pagination']['nextPageUrl']
               if next_page:
                   yield scrapy.Request(next_page, callback=self.parse, meta={'pos': pos})

                   #scrapy crawl pageSearch -o test.json

我使用Windows 10。另外,我请求您的帮助,谢谢!

a2mppw5e

a2mppw5e1#

我发现了两个问题:

名字:

在输出中,您可以看到

[scrapy.downloadermiddlewares.robotstxt] DEBUG: Forbidden by robots.txt: <GET https://www.ask.com/web?q=love>

这意味着它读取https://www.ask.com/robots.txt并且存在规则

User-agent: *
Disallow: /web

Scrapy尊重它并且跳过url https://www.ask.com/web?q=love
您必须在您的www.example.com中设置ROBOTTXT_OBEY = Falsesettings.py才能关闭它。
报废文件:ROBOTTXT_OBEY

第二个:

您使用di = json.loads(response.text),这意味着您需要JSON数据,但此页面发送HTML,您必须使用函数response.css(...)response.xpath(...).get().attrib.get(...)等。
报废文档:Selectors
工作代码:
您可以将所有代码放在一个script.py文件中,并以python script.py身份运行,而无需创建项目它还将自动将结果保存在test.json中,而无需使用-o test.json

import scrapy
import datetime

class PagesearchSpider(scrapy.Spider):

    name = 'pageSearch'

    def start_requests(self):
        queries = [ 'love']
        for query in queries:
            url = 'https://www.ask.com/web?q='+query
            yield scrapy.Request(url, callback=self.parse, meta={'pos': 0})

    def parse(self, response):
        print('url:', response.url)

        start_pos = response.meta['pos']
        print('start pos:', start_pos)

        dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')    

        items = response.css('div.PartialSearchResults-item')

        for pos, result in enumerate(items, start_pos+1):
            yield {
                'title':    result.css('a.PartialSearchResults-item-title-link.result-link::text').get().strip(), 
                'snippet':  result.css('p.PartialSearchResults-item-abstract::text').get().strip(), 
                'link':     result.css('a.PartialSearchResults-item-title-link.result-link').attrib.get('href'), 
                'position': pos, 
                'date':     dt,
            }

        # --- after loop ---

        next_page = response.css('.PartialWebPagination-next a')

        if next_page:
            url = next_page.attrib.get('href')
            print('next_page:', url)  # relative URL
            # use `follow()` to add `https://www.ask.com/` to URL and create absolute URL
            yield response.follow(url, callback=self.parse, meta={'pos': pos+1})

# --- run without project, and save in file ---

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    #'USER_AGENT': 'Mozilla/5.0',
    # save in file CSV, JSON or XML
    'FEEDS': {'test.json': {'format': 'json'}},
    #'ROBOTSTXT_OBEY': True,  # this stop scraping
})
c.crawl(PagesearchSpider)
c.start()

相关问题