【问题标题】:How to access/set 'select' tag in HTML with python如何使用 python 在 HTML 中访问/设置“选择”标签
【发布时间】:2015-07-04 09:53:19
【问题描述】:

我正在尝试从 HTML 页面中提取事件 - http://www.staffordshire-pcc.gov.uk/space/

我想使用 python 选择不同的区域,但遇到以下 HTML:

<select data-ng-options="key as value.name for (key,value) in areaGroups | orderBy:'name'" data-ng-model="selectedAreaGroup" data-ng-change="updateAreaGroup()" class="ng-pristine ng-valid ng-touched">
    <option value="" class="" selected="selected">Choose an area</option>
    <option value="string:CannockChase" label="Cannock Chase District">Cannock Chase District</option>
    <option value="string:EastStaffordshire" label="East Staffordshire">East Staffordshire</option>
    <option value="string:Lichfield" label="Lichfield District">Lichfield District</option>
    <option value="string:Newcastle" label="Newcastle Borough">Newcastle Borough</option>
    <option value="string:SouthStaffordshire" label="South Staffordshire">South Staffordshire</option>
    <option value="string:Stafford" label="Stafford Borough">Stafford Borough</option>
    <option value="string:StaffordshireMoorlands" label="Staffordshire Moorlands">Staffordshire Moorlands</option>
    <option value="string:SoTCentral" label="Stoke-on-Trent Central">Stoke-on-Trent Central</option>
    <option value="string:SoTNorth" label="Stoke-on-Trent North">Stoke-on-Trent North</option>
    <option value="string:SoTSouth" label="Stoke-on-Trent South">Stoke-on-Trent South</option>
    <option value="string:Tamworth" label="Tamworth Borough">Tamworth Borough</option>

我使用 Mechanize 在页面上查找表单,但由于标签没有附加表单,我无法确定如何选择它,然后提交一个值。

什么是我追求的最佳选择?

【问题讨论】:

    标签: python html selenium web-scraping mechanize


    【解决方案1】:

    您可以按照表格在页面上出现的顺序选择表格,先导入打开

    import mechanize
    br = mechanize.Browser()
    br.open('http://www.staffordshire-pcc.gov.uk/space/')
    

    循环浏览页面中的所有表单

    forms = [f.name for f in br.forms()]
    

    让我们检查 form[0] 是否是带有下拉列表的表单的正确索引(如您的问题)设置控制变量并打印出值

    control = forms[0].controls[0]
    form_values = [item.attrs['value'] for item in control.items]
    print form_values
    

    如果这是您应该看到的正确形式:

    ["string:CannockChase", "string:EastSta....
    

    如果不循环遍历索引,直到找到正确的索引(* 见下文)。

    最后,一旦你找到了正确的表单,你就可以设置一个值并提交:

    br.form[0*] = form_values[0]
    r = br.submit()
    // read out the HTML from the resulting page
    print r.read()
    

    * 此索引是您问题中代表下拉表单的任何一个

    【讨论】:

    • 我已经完成了一半,但无法计算出 item.attrs['value'] 位。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多