【问题标题】:Can I use requests.post to submit a form?我可以使用 requests.post 提交表单吗?
【发布时间】:2018-02-03 00:02:25
【问题描述】:

我正在尝试从此站点获取商店列表: http://www.health.state.mn.us/divs/cfh/wic/wicstores/

我想获取单击“查看所有商店”按钮时生成的商店列表。我知道我可以使用 Selenium 或 MechanicalSoup 或 ... 来执行此操作,但我希望使用请求。

看起来点击按钮提交表单:

 <form name="setAllStores" id="setAllStores" action="/divs/cfh/wic/wicstores/index.cfm" method="post" onsubmit="return _CF_checksetAllStores(this)">
<input name="submitAllStores" id="submitAllStores"  type="submit" value="View All Stores" />

但我不知道如何编写请求查询(或者实际上是否可能)。

我到目前为止尝试的原因是:

SITE = 'http://www.health.state.mn.us/divs/cfh/wic/wicstores/'
data = {'name': 'setAllStores', 'form': 'submitAllStores', 'input': 'submitAllStores'}
r = requests.post(SITE, data)

但这不起作用。欢迎任何帮助/建议。

【问题讨论】:

  • 尝试写requests.post(SITE, payloads = data) 希望这能解决您的问题
  • 1) 在表单的 action 属性中使用 url,2) 发布此数据 {'submitAllStores': 'View All Stores'}
  • 其实url应该没问题的,换个post数据就好了。
  • 谢谢 t.m.亚当。那成功了。如果你有两分钟的时间,如果你能解释我哪里出错了,我会学到很多东西。感谢您的帮助。
  • 是的,在您的 data 字典中,您应该有表单输入的名称和值。表单“操作”是提交表单的地方。如果您有任何问题,请提出。

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

如果您考虑选择view all stores 选项,请尝试以下代码填充结果。

import requests
from bs4 import BeautifulSoup

FormData={
    'submitAllStores':'View All Stores'
}
with requests.Session() as s:
    s.headers = {"User-Agent":"Mozilla/5.0"}
    res = s.post("http://www.health.state.mn.us/divs/cfh/wic/wicstores/index.cfm",data=FormData)
    soup = BeautifulSoup(res.text, 'lxml')
    for item in soup.select(".info"):
        shopname = item.select_one(".info-service").text
        print(shopname)

部分输出:

1st Quality Market
33rd Meat & Grocery
52 Market  And Trading
75 Market And Deli
7th Grocery
9th Ave X-Press

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2013-09-19
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    相关资源
    最近更新 更多