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")
Or set some text input:
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>
The QWebKit
classes use CSS2 selector syntax to find elements.
So the required option could be found like this:
doc = webview.page().mainFrame().documentElement()
option = doc.findFirst('select[name="birthday_m"] > option[value="3"]')
and then the selected
attribute can be set on the option element like this:
option.setAttribute('selected', 'true')
However, for some reason, this does not immediately update the page (and nor does calling webview.reload()
).
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')
I did it this way :
doc.evaluateJavaScript('document.getElementsByName("birthdate_m")[0].options[3].selected = true')
If you have any suggestions, on how to improve it, please let me knnow.