python - 将 Mechanize 与不在表单内的选择字段一起使用?

标签 python web-scraping mechanize

我想使用 Mechanize (with 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>

最佳答案

这实际上比您想象的要复杂,但仍然很容易实现。发生的情况是您链接的网页正在通过 JSON 拉入地方当局(这就是为什么 name="la" select 元素没有填写缺少 Javascript 的 Mechanize)。最简单的方法是直接用 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 来完成!但是,您仍然需要一种方法来解析学校名称,然后是绩效数据。

关于python - 将 Mechanize 与不在表单内的选择字段一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11034896/

相关文章:

python - 使用 ipython 小部件增加计数器

python - 如何测试该变量不等于多个事物?

ruby-on-rails-3 - 轨道 3 : Choose and run a Mechanize script from inside Rails action.

python - 从 Plotly 中的 DataFrame 列添加多个文本标签

python - 使用 NewsAPI.org 通过 HTTP 请求传递多个关键字

python - 如何模拟点击 "Next"直到结束?

python - 想抓取flipkart

python - 使用报纸时如何按类别过滤文章?

python - 使用 mechanize Python 登录 Dropbox

perl - 让 Mechanize 返回值的问题,甚至是错误消息,啊!