机械化如何添加到选择列表?

2024-07-01 07:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始尝试通过mechanize提交webforms。在this webpage上有一个项目列表可供选择,MASTER_MODS。可以在MODS中使用butten add_MODS或使用按钮add_IT_MODS在{}中选择(参见底部的图)。在表单中如下所示(底部表单的代码):

 <<SNIP>>
<SelectControl(MODS=[*--- none selected ---])>
<IgnoreControl(add_MODS=<None>)>
<SelectControl(MASTER_MODS=[])>
<SelectControl(IT_MODS=[*--- none selected ---])>
<IgnoreControl(remove_IT_MODS=<None>)>
<IgnoreControl(add_IT_MODS=<None>)>
<<SNIP>>

所以我想添加到<SelectControl(MODS=[*--- none selected ---])><SelectControl(IT_MODS=[*--- none selected ---])>。但是,当我尝试使用

^{pr2}$

我得到mechanize._form.ItemNotFoundError: insufficient items with name 'Acetyl (N-term)'

当我试着

br.form[ 'add_MODS'] = 'Acetyl (N-term)'

我得到ValueError: control 'add_MODS' is ignored, hence read-only。在

如何向MODSIT_MODS添加项目?在


图形和代码enter image description here

代码:

from mechanize import Browser, _http
br = Browser()    
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
url = "http://www.matrixscience.com/cgi/search_form.pl?FORMVER=2&SEARCH=MIS"
br.select_form( 'mainSearch' )
br.open(url)
print br.form

Tags: 项目代码brformmasternoneaddmods
1条回答
网友
1楼 · 发布于 2024-07-01 07:20:48

试试这个?评论中的解释。在

from mechanize import Browser, Item
br = Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent',
                  'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)'
                  ' Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
url = 'http://www.matrixscience.com'\
      '/cgi/search_form.pl?FORMVER=2&SEARCH=MIS'
br.open(url)
br.select_form('mainSearch')

# get the actual control object instead of its contents
mods = br.find_control('MODS')
# add an item
item = Item(mods, {"contents": "Acetyl (N-term)", "value": "Acetyl (N-term)"})
# select it. if you don't, it doesn't appear in the output
# this is probably why MASTER_MODS appears empty
item.selected = True
print br['MODS']
# outputs: ['Acetyl (N-term)']

假设这是可行的,我是从the docs中的评论中得到的:

To add items to a list container, instantiate an Item with its control and attributes: Note that you are responsible for getting the attributes correct here, and these are not quite identical to the original HTML, due to defaulting rules and a few special attributes (e.g. Items that represent OPTIONs have a special "contents" key in their .attrs dict). In future there will be an explicitly supported way of using the parsing logic to add items and controls from HTML strings without knowing these details. mechanize.Item(cheeses, {"contents": "mascarpone", "value": "mascarpone"})

相关问题 更多 >

    热门问题