如何在Python的requests库中使用Splash?

3

我想在requests中使用Splash,类似于这样的操作:

requests.post(myUrl,headers=myHeaders, data=payload, meta={
                                        'splash': {
                                            'endpoint': 'render.html',
                                            'args': {'wait': 1}
                                            }
                                        })

但是我遇到了这个错误。

TypeError: request() got an unexpected keyword argument 'meta'

我知道这可以使用 scrapy.Request 实现,但我想使用 requests 实现。

1个回答

12

meta 是 Scrapy Request 特有的,而 python-requests 的 request 没有 meta 参数,因此会引发 TypeError 异常。

要使用 Splash 和 python-requests,阅读 HTTP API 文档,特别是关于 render.html 的部分。看起来这正是你想要使用的东西。

你需要对 /render.html 端点进行 GET 请求,并将目标 URL 和 wait 参数作为查询参数传递,例如:

import requests
requests.get('http://localhost:8050/render.html',
             params={'url': 'http://www.example.com', 'wait': 2})

如果您想让Splash向目标网站发出POST请求,请使用http_methodbody参数:

import requests
requests.get('http://localhost:8050/render.html',
              params={'url': 'http://httpbin.org/post',
                      'http_method': 'POST',
                      'body': 'a=b',
                      'wait': 2})

/render.html同时允许向端点发出POST请求

Splash可以通过HTTP API进行控制。对于下面的所有端点,参数既可以作为GET参数发送,也可以编码为JSON并使用Content-Type: application/json头进行POST。

但默认方法仍然是GET。要向目标网站发送POST,仍需要包括http_method参数:

import requests

requests.post('http://localhost:8050/render.html',
              json={'url': 'http://httpbin.org/post',
                    'http_method': 'POST',
                    'body': 'a=b',
                    'wait': 2})

但我应该发送一个POST请求。 - parik
你的意思是Splash应该向目标网站发出POST请求吗?如果是的话,/render.html提供了http_methodbody参数 - paul trmbrth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接