2012-06-14 32 views
0

我想使用Mechanize(使用Python)提交表单,但不幸的是页面编码严重且<select>元素实际上并不在<form>标签内。使用机械化与不在表单内的选择字段?

所以我无法通过形式使用传统的方法:

forms = [f for f in br.forms()] 
mycontrol = forms[1].controls[0] 

我能做些什么呢?

这里是page I would like to scrape,以及相关的代码位 - 我感兴趣的la选择项:

<fieldset class="searchField"> 
     <label>By region/local authority</label> 
     <p id="regp"> 
     <label>Region</label> 
     <select id="region" name="region"><option></option></select> 
     </p> 
     <p id="lap"> 
     <label>Local authority</label> 
     <select id="la" name="la"><option></option></select> 
     </p> 
     <input id="byarea" type="submit" value="Go" /> 
     <img id="regmap" src="/schools/performance/img/map_england.png" alt="Map of regions in England" border="0" usemap="#England" /> 
    </fieldset> 

回答

1

这实际上是比较复杂的,你想,但还是很容易实现。正在发生的事情是,您链接的网页正在通过JSON拉入当地政府机构(这就是为什么name="la" select元素没有填充Mechanize,它缺少Javascript)。最简单的方法是直接用Python请求这个JSON数据,并使用结果直接进入每个数据页面。

import urllib2 
import json 

#The URL where we get our array of LA data 
GET_LAS = 'http://www.education.gov.uk/cgi-bin/schools/performance/getareas.pl?level=la&code=0' 

#The URL which we interpolate the LA ID into to get individual pages 
GET_URL = 'http://www.education.gov.uk/schools/performance/geo/la%s_all.html' 

def get_performance(la): 
    page = urllib2.urlopen(GET_URL % la) 
    #print(page.read()) 

#get the local authority list 
las = json.loads(urllib2.urlopen(GET_LAS).read()) 

for la in las: 
    if la != 0: 
     print('Processing LA ID #%s (%s)' % (la[0], la[1])) 
     get_performance(la[0]) 

正如你所看到的,你甚至不需要加载你链接的页面或使用Mechanize来做到这一点!但是,您仍然需要一种方法来解析出学校名称,然后再分析表现数字。

+0

非常感谢!我应该意识到,如果没有'

'外部元素,它不可能提交表单,因此必须是链接。 – flossfan