【问题标题】:differentiating between html form SELECT items with the same name区分具有相同名称的html表单SELECT项目
【发布时间】:2011-06-26 18:49:00
【问题描述】:

我正在尝试使用 Mechanize 在 Python 中动态填写表单。但是,当我检查包含表单的 HTML 页面的源代码时,我意识到表单上的某些控件具有相同的名称。以下是表格的摘录:

<form action="[some website]" method=post>
<table>
    <tr><td>
        <select NAME="mv_searchspec" size="1">      
            <option VALUE="1119">Fall 2011 (1119)</option> 
            <!-- other options here -->
        </select>
    </tr><td>
    <tr><td>
        <select NAME="mv_searchspec" size="1"> 
            <option VALUE="">Select Department</option> 
            <option VALUE="ACC">ACC</option> 
            <!-- other options here -->
        </select>
    </tr></td>
</table>
</form>

有没有办法获取每个 SELECT 控件的 possible_items 而不用名称/id 来识别它们?

【问题讨论】:

  • 很可能有一种方法,尽管它是特定于后端的。在 PHP 中,最后一个值会覆盖其他值(除非名称以[] 结尾,例如my_searchspec[],在这种情况下my_searchspec 可以作为数组访问);在 ColdFusion 中,这些值用逗号分隔。

标签: python html mechanize


【解决方案1】:

您可以使用BeautifulSoup 解析响应以获取选择选项

import mechanize
from BeautifulSoup import BeautifulSoup
br = mechanize.Browser()
resp = br.open('your_url')
soup = BeautifulSoup(resp.get_data())
second_select = soup.findAll('select', name="mv_searchspec")[1]
# now use BeautifulSoup API to get the data you want

你不能做像br['mv_searchspec'] = 'foo' 这样的事情,因为这显然是模棱两可的。不过你应该可以做到这一点

br.select_form(nr=0) # select index
controls = br.form.controls
controls[desired_index]._value = 'your_value'
...
br.submit()

【讨论】:

    【解决方案2】:

    正如 zneak 所说,处理是特定于后端的。要意识到的重要一点是,每个具有指定属性“名称”的元素都将通过 POST/GET 发送,即使它是空的。因此,区分它们的方法很简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多