如何使用PyQt4.QtWebKit从选项列表中选择值 [英] How to choose value from an option list using PyQt4.QtWebKit

查看:106
本文介绍了如何使用PyQt4.QtWebKit从选项列表中选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用PyQt4.QtWebKit从网站上的选项列表中自动选择一个生日,但是我在执行此操作时遇到了麻烦.

I'm trying to auto-select a birthday from an option list on my website by using PyQt4.QtWebKit, but I'm having trouble doing this.

要选择单选按钮时,请执行以下操作:

When I want to select a radio button I do this:

doc = webview.page().mainFrame().documentElement()
g = doc.findFirst("input[id=gender]")
g.setAttribute("checked", "true")

或设置一些文本输入:

doc = webview.page().mainFrame().documentElement()
s = doc.findFirst("input[id=say_something]")
s.setAttribute("value", "Say Hello To My Little Friends")

但是如何从该选项列表中选择一个月?

But how do I select a month from this option list?

<select tabindex="11" name="birthday_m">
 <option value="">---</option>
 <option value="1">JAN</option>
 <option value="2">FEB</option>
 <option value="3">MAR</option>
</select>

推荐答案

QWebKit类使用 CSS2选择器语法以查找元素.

因此可以找到所需的选项,如下所示:

So the required option could be found like this:

doc = webview.page().mainFrame().documentElement()
option = doc.findFirst('select[name="birthday_m"] > option[value="3"]')

,然后可以在选项元素上设置selected属性,如下所示:

and then the selected attribute can be set on the option element like this:

option.setAttribute('selected', 'true')

但是,由于某种原因,这不会立即更新页面(也不会调用webview.reload()).

However, for some reason, this does not immediately update the page (and nor does calling webview.reload()).

因此,如果您需要立即更新,则更好的方法可能是获取select元素:

So if you need an immediate update, a better way might be to get the select element:

doc = webview.page().mainFrame().documentElement()
select = doc.findFirst('select[name="birthday_m"]')

,然后按如下所示设置选定的选项:

and then set the selected option like so:

select.evaluateJavaScript('this.selectedIndex = 3')

这篇关于如何使用PyQt4.QtWebKit从选项列表中选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆