pythonqtpyqt4qtwebkit

How to choose value from an option list using 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")

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>

Solution

  • 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')