如何在机械化中单击表单中的标签?

时间:2014-11-07 02:33:12

标签: python mechanize

<p class="field switch">
            <label id="on" class="cb-enable"><span>On</span></label>
            <label id="off" class="cb-disable selected"><span>Off</span></label>
</p>

任何想法我如何点击标签id =&#34; on&#34;?它是一个我希望从关闭切换到开启的开关,通过单击&#34; on&#34;标签

我尝试的事情:

br.form.get(label="On").click()
br.form.find_control(id="on").click()

文档:http://wwwsearch.sourceforge.net/mechanize/forms.html

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

Mechanize没有javascript支持,因此没有触发点击事件。此外,您显示的HTML不包含输入元素,因此机械化无法对其执行任何操作。

如果此网站确实需要Javascript,我建议您使用WatirSeleniumScrapy ScrapyJS

使用Mechanize,您可以手动编辑响应,如下所示:

import mechanize

class ReplacingOpener(mechanize.SeekableResponseOpener):
    def process_response_object(self, response):
        response = mechanize.SeekableResponseOpener.process_response_object(
            self, response)

        # Get the HTML from the response
        html = response.read()

        # Replace the HTML here with anything you feel like
        html = html.replace('</body>', '')

        # Set it back to the response
        response.set_data(html)
        return response


opener = mechanize.OpenerFactory(ReplacingOpener).build_opener()
response = opener.open('http://stackoverflow.com/questions/26793091/')

forms = mechanize.ParseResponse(response)
print forms

答案 1 :(得分:0)

机械化有点棘手(参见@ Wolph的回答)。

为什么你说硒有些过度?它看起来像这样:

from selenium import webdriver
url = "http://www.dummy.com/page.html"
click_id = 'on'
driver = webdriver.Firefox()
driver.get(url)
driver.find_element_by_id(click_id).click()
new_page = driver.page_source