首页 > 解决方案 > 无法以正确的方式使我的脚本处理本地创建的服务器响应

问题描述

我使用了一个脚本在本地运行 selenium,这样我就可以在我的蜘蛛中使用响应(来自 selenium)。

这是 selenium 在本地运行的 Web 服务:

from flask import Flask, request, make_response
from flask_restful import Resource, Api
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

app = Flask(__name__)
api = Api(app)

class Selenium(Resource):
    _driver = None

    @staticmethod
    def getDriver():
        if not Selenium._driver:
            chrome_options = Options()
            chrome_options.add_argument("--headless")

            Selenium._driver = webdriver.Chrome(options=chrome_options)
        return Selenium._driver

    @property
    def driver(self):
        return Selenium.getDriver()

    def get(self):
        url = str(request.args['url'])

        self.driver.get(url)

        return make_response(self.driver.page_source)

api.add_resource(Selenium, '/')

if __name__ == '__main__':
    app.run(debug=True)

这是我的爬虫蜘蛛,它利用该响应来解析网页的标题。

import scrapy
from urllib.parse import quote
from scrapy.crawler import CrawlerProcess

class StackSpider(scrapy.Spider):
    name = 'stackoverflow'
    url = 'https://stackoverflow.com/questions/tagged/web-scraping?sort=newest&pageSize=50'
    base = 'https://stackoverflow.com'

    def start_requests(self):
        link = 'http://127.0.0.1:5000/?url={}'.format(quote(self.url))
        yield scrapy.Request(link,callback=self.parse)

    def parse(self, response):
        for item in response.css(".summary .question-hyperlink::attr(href)").getall():
            nlink = self.base + item
            link = 'http://127.0.0.1:5000/?url={}'.format(quote(nlink))
            yield scrapy.Request(link,callback=self.parse_info,dont_filter=True)

    def parse_info(self, response):
        item = response.css('h1[itemprop="name"] > a::text').get()
        yield {"title":item}

if __name__ == '__main__':
    c = CrawlerProcess()
    c.crawl(StackSpider)
    c.start()

问题是上面的脚本多次给我相同的标题,然后是另一个标题,依此类推。

为了使我的脚本以正确的方式工作,我应该带来哪些可能的变化?

标签: pythonpython-3.xflaskweb-scrapingscrapy

解决方案


我运行了两个脚本,它们按预期运行。所以我的发现:

  1. downloader/exception_type_count/twisted.internet.error.ConnectionRefusedError没有服务器的许可,没有办法解决这个错误,这里就是 ebay。

  2. 来自scrapy的日志:

    2019-05-25 07:28:41 [scrapy.statscollectors] 信息:转储 Scrapy 统计信息:{'downloader/exception_count': 72, 'downloader/exception_type_count/twisted.internet.error.ConnectionRefusedError': 64, 'downloader/exception_type_count /twisted.web._newclient.ResponseNeverReceived': 8, 'downloader/request_bytes': 55523, 'downloader/request_count': 81, 'downloader/request_method_count/GET': 81, 'downloader/response_bytes': 2448476, 'downloader/response_count ': 9, 'downloader/response_status_count/200': 9, 'finish_reason': 'shutdown', 'finish_time': datetime.datetime(2019, 5, 25, 1, 58, 41, 234183), 'item_scraped_count': 8 , 'log_count/DEBUG': 90, 'log_count/INFO': 9, 'request_depth_max': 1, 'response_received_count': 9, '重试/计数':72,'重试/reason_count/twisted.internet.error.ConnectionRefusedError':64,'重试/reason_count/twisted.web._newclient.ResponseNeverReceived':8,'调度程序/出队':81,'调度程序/ dequeued/memory': 81, 'scheduler/enqueued': 131, 'scheduler/enqueued/memory': 131, 'start_time': datetime.datetime(2019, 5, 25, 1, 56, 57, 751009)} 2019- 05-25 07:28:41 [scrapy.core.engine] 信息:蜘蛛关闭(关闭)1、56、57、751009)} 2019-05-25 07:28:41 [scrapy.core.engine] 信息:蜘蛛关闭(关闭)1、56、57、751009)} 2019-05-25 07:28:41 [scrapy.core.engine] 信息:蜘蛛关闭(关闭)

你只能看到8被刮掉的物品。这些只是徽标和其他不受限制的东西。

  1. Server Log

    s:// .ebaystatic.com http:// .ebay.com https://*.ebay.com"。'unsafe-inline' 关键字,哈希 ('sha256-40GZDfucnPVwbvI/Q1ivGUuJtX8krq8jy3tWNrA/n58=') , 或者需要一个 nonce ('nonce-...') 才能启用内联执行。”,来源:https ://vi.vipr.ebaydesc.com/ws/eBayISAPI.dll?ViewItemDescV4&item=323815597324&t=0&tid=10&category= 169291&seller=wardrobe-ltd&excSoj=1&excTrk=1&lsite=0&ittenable=false&domain=ebay.com&descgauge=1&cspheader=1&oneClk=1&secureDesc=1 (1)

易趣不允许你自己

那么如何完成你的任务>>

  1. 每次在刮检查/robots.txt同一个站点之前。对于 ebay 它:http ://www.ebay.com/robots.txt 你可以看到几乎所有的东西都是不允许的。

    用户代理:* 禁止:/*rt=nc 禁止:/b/ LH_ 禁止:/brw/ 禁止:/clp/ 禁止:/clt/store/ 禁止:/csc/ 禁止:/ctg/ 禁止:/ctm/不允许:/dsc/ 不允许:/edc/ 不允许:/feed/ 不允许:/gsr/ 不允许:/gwc/ 不允许:/hcp/ 不允许:/itc/ 不允许:/lit/ 不允许:/lst/ng/ 不允许:/ lvx/ 禁止:/mbf/ 禁止:/mla/ 禁止:/mlt/ 禁止:/myb/ 禁止:/mys/ 禁止:/prp/ 禁止:/rcm/ 禁止:/sch/ %7C 禁止:/sch/ LH_禁止:/sch/aop/ 禁止:/sch/ctg/ 禁止:/sl/node 禁止:/sme/ 禁止:/soc/ 禁止:/talk/ 禁止:/tickets/ 禁止:/today/ 禁止:/trylater/禁止:/urw/write-review/ 禁止:/vsp/ 禁止:/ws/ 禁止:/sch/ modules=SEARCH_REFINEMENTS_MODEL_V2 禁止:/b/modules=SEARCH_REFINEMENTS_MODEL_V2 Disallow: /itm/ _nkw Disallow: /itm/ ?fits Disallow: /itm/&fits Disallow: /cta/

  2. 因此,请访问https://developer.ebay.com/api-docs/developer/static/developer-landing.html并查看他们的文档,他们的网站中有更简单的示例代码可以在不抓取的情况下获得项目需求。


推荐阅读