区分具有相同名称的HTML表单SELECT项

1 投票
2 回答
1193 浏览
提问于 2025-04-16 20:18

我正在用Python的Mechanize库动态填写一个表单。不过,当我查看这个表单的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>

有没有办法在不通过名字或ID来识别的情况下,获取每个下拉框(SELECT控件)里的可能选项(possible_items)呢?

2 个回答

0

正如zneak所说,处理方式是和后台有关的。重要的是要明白,所有带有'name'属性的元素都会通过POST或GET发送,即使它们是空的。因此,区分这些元素的方法就是看它们的顺序。

5

你可以使用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()

撰写回答