【问题标题】:multipart-form-data, POST method, with multiples forms in the pagemultipart-form-data,POST 方法,页面中有多个表单
【发布时间】:2018-11-18 14:51:06
【问题描述】:

问题

我正在尝试使用 request 的 python 库在页面中进行 scraping,但是我遇到了错误(例如 错误的请求不允许的方法)。

  • 该页面有两种形式:一种带有 get,另一种带有 post(我希望如此)。我确实使用“数据请求”将值传递给文本字段。

  • 我不想为表单传递图像,只是一个文本字段。

  • 表单中有六个按钮,每个按钮都有不同的值。


HTML 代码

<form enctype="multipart/form-data" action="/page1" method="GET"> ... </form>
...
<form enctype="multipart/form-data" action="/page2" method="POST"> 
  <input type="file" name="smiles_file">
  <input type="text" name="smiles_str">
  ...
  <button name="pred_type" type="submit" value="adme"> BT1 </button>
  <button name="pred_type" type="submit" value="toxicity"> BT2 </button>
</form>

Python3 代码

#imports
import requests
from bs4 import BeautifulSoup as bs

#commmon vars
url = 'www.exampleurl.com/site'
hd  = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36"
}
dt  = {
'smiles_str': 'CC(=O)OC1=CC=CC=C1C(=O)O',
'pred_type': 'adme'
}

#scraping
with requests.Session() as rs:
    result = rs.get(url, data=dt, headers=hd)
    print ("Code: %s\nHTML\n%s" % (result.status_code, result.text))

编辑

使用获取: status_code:405(方法...) 使用帖子: status_code: 400(错误请求)

【问题讨论】:

  • rs.get?应该是 rs.post

标签: python python-3.x web-scraping python-requests multiple-forms


【解决方案1】:

在您的示例中,我没有看到对 /page1/page2 的引用,但 rs.get 可能应该使用命名参数 params 而不是 data 并且应该对应于第一个表单 URL ,而对于第二种形式的 URL,您需要使用 rs.post 方法,其中使用数据是可以的。

【讨论】:

  • 我确实使用了post,但是我遇到了错误,所以我尝试使用get,但又遇到了另一个错误。我用相应的错误更新了问题。 对不起。关于这一点:“我在您的示例中没有看到对 /page1 或 /page2 的引用”。两种形式都在页面内:www.exampleurl.com/site 所以我有 7 个按钮,6 个带有第二个表单的值,一个用于第一个表单。
  • @PedroAugusto 当您在浏览器中加载 exampleurl.com/site 并填写 form enctype="multipart/form-data" action="/page1" method="GET" 的表单字段并按提交时,提交的多部分数据将作为参数添加到 GET 请求中exampleurl.com/page1 通过您的浏览器。这是您需要在代码中复制的行为。
  • 我真正想要的表单是 post,我尝试使用页面的 url 以及操作 url,并且在这两种情况下,都像我之前所说的那样返回错误:. 使用 get: status_code: 405 (Method ... ) 使用 post: status_code: 400 (Bad request)
【解决方案2】:

我想我找到了答案。似乎 selenium 在使用 js 背景的页面上效果不佳。我正在使用 selenium,我没有遇到任何问题。

【讨论】:

  • 嗨,欢迎来到 Stack Overflow。您回答的措辞没有意义:您说 Selenium 不能很好地与某些 JS 功能一起使用,然后您说您正在使用 Selenium,并且没有任何问题。第二句在逻辑上与第一句不同。
猜你喜欢
  • 2011-04-22
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 2019-04-05
  • 2022-07-29
  • 1970-01-01
  • 2021-08-03
  • 2019-07-08
相关资源
最近更新 更多