scrapy Python的简易版本requests.post

quhf5bfb  于 2022-11-09  发布在  Python
关注(0)|答案(1)|浏览(119)

我正在向一个特定的端点发出请求,添加一些头文件和一个json,使用python请求。

我的Json数据

json_data = {
    'query': '',
    'page_size': 20,   # IMPORTANT FIELD
    'page_token': '0',   # IMPORTANT FIELD
    'sponsored_results_max': 2,    # IMPORTANT FIELD
    'locales': [       # IMPORTANT FIELD: We can use it to control the language
    'en', 'fr', 'de',
    ],
    'contract_types': [
    'alternating',
    'alternating',
    'berufsbegleitendes_studium',
    'job',
    'cdd',
    'cdi',
    'graduate_program',
    'vie',
    'part_time',
    'stage',
    'internship',
    'werkstudent',
    'thesis',
    'thesis',
    ],
    'school_ids': [
    '0',
    ],
    'curriculum_ids': None,
    'career_center_study_levels': [],
}

原始请求

会给我所需的回应

response = requests.post(endpoint, headers=headers, json=json_data)
response.json()

我想要的回应(简短地说,因为原始档案比较大)

...{'parent_name': 'locale', 'name': 'es', 'count': 22}, {'parent_name': 'locale', 'name': 'it', 'count': 17}, {'parent_name': 'locale', 'name': 'fi', 'count': 7}, {'parent_name': 'locale', 'name': 'sv', 'count': 2}, {'parent_name': 'locale', 'name': 'pt', 'count': 1}, {'parent_name': 'school_ids', 'name': '0', 'count': 12982}...

没有给我预期回应的蹩脚选择#

第一次失败

from scrapy.http import JsonRequest

j_response = JsonRequest(url=endpoint, headers=headers, data=json_data)
j_response.to_dict()

第二次失败

from scrapy import Request

sc_response = Request(method='POST', url=endpoint, headers=headers, body=json.dumps(json_data))
sc_response.to_dict()
nxagd54h

nxagd54h1#

当您使用requests库调用requests.postrequests.get时,您既创建了一个请求对象,又执行了一个类似于获取的过程,该过程获取了从这些调用返回的响应。
当你创建一个scrapy.Request时,它只创建请求示例并返回它。获取部分由crawler和scrapy引擎完成,scrapy引擎在scrapy.Spider构建请求后接收请求。
所以在你的两个例子中,sc_responsej_response变量仍然只是请求对象,它们只包含你提供给构造函数的信息。如果你想让scrapy从URI中获取数据,你可能需要创建一个Spider来获取它们。
此外,如果您正在处理scrapy.Response对象,它们具有与request.Response相同的json()方法,因此您可能希望使用该方法来获取格式化的json数据。
例如:

import scrapy

class QuotesSpider(scrapy.Spider):
    name = 'spider'

    def start_requests(self):
        sc_request = Request(method='POST', url=endpoint, headers=headers, body=json.dumps(json_data))
        yield sc_request

    def parse(self, response):
        yield response.json()

相关问题