ZetCode

Python pyquery

last modified November 18, 2026 Python 3.15

In this article we show how to make jQuery-like queries on HTML and XML documents in Python with the pyquery library.

jQuery is a JavaScript library for manipulating the DOM. With jQuery we can find, select, traverse, and modify parts of an HTML document using CSS selectors and a chainable API.

pyquery brings the same API to Python. It is built on top of lxml, which does the parsing, and cssselect, which translates CSS selectors to XPath. A PyQuery object wraps a list of lxml elements; most methods return a new PyQuery object, so calls can be chained like in jQuery.

The examples were tested with Python 3.15, pyquery 2.1.0, lxml 6.1.3, and cssselect 1.6.0. The web scraping example also uses the requests library.

$ pip install pyquery requests

The HTML document

Most examples work with the following HTML document. It contains a heading, a list of operating systems with id, class, and style attributes, and a paragraph with two links.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Operating systems</title>
</head>
<body>
    <h2>Operating systems</h2>

    <ul id="oslist" class="systems" style="width:150px">
        <li class="unix">Solaris</li>
        <li class="bsd">FreeBSD</li>
        <li class="linux">Debian</li>
        <li class="bsd">NetBSD</li>
        <li>Windows</li>
    </ul>

    <p>
        More at <a href="https://www.debian.org/">Debian</a> and
        <a href="https://www.freebsd.org/">FreeBSD</a> websites.
    </p>
</body>
</html>

The file is saved as index.html in the same directory as the Python scripts.

Loading a document

The PyQuery constructor accepts an HTML string, a file name via the filename keyword, or a URL via the url keyword. Calling the resulting object with a CSS selector returns the matching elements.

header.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')

print(doc('title').text())
print(doc('h2').text())

The example loads the document from a file and prints the text of the title and h2 elements.

from pyquery import PyQuery as pq

By convention, the PyQuery class is imported under the short name pq, which resembles jQuery's $.

doc = pq(filename='index.html')

The filename keyword tells pyquery to read and parse the file.

print(doc('title').text())

Calling doc with the title selector returns a PyQuery object with the matching elements; the text method returns their text content.

$ python header.py
Operating systems
Operating systems

Parsing a string

When we already have the HTML in a string, for example from a file we read ourselves or from an HTTP response, we pass it directly to the constructor.

from_string.py
from pyquery import PyQuery as pq

with open('index.html', encoding='utf-8') as f:
    contents = f.read()

doc = pq(contents)

print(type(doc))
print(len(doc('li')))
print(doc('li').eq(0).outer_html())

snippet = pq('<div><span>pyquery</span> parses fragments too</div>')
print(snippet('span').text())

We read the file contents into a string and parse it. Then we parse a small HTML fragment as well.

print(len(doc('li')))
print(doc('li').eq(0).outer_html())

A PyQuery object behaves like a list of elements, so len returns the number of matches. The eq method selects the element at the given index and outer_html returns its markup including the element's own tag.

snippet = pq('<div><span>pyquery</span> parses fragments too</div>')

A fragment does not need to be a complete document.

$ python from_string.py
<class 'pyquery.pyquery.PyQuery'>
5
<li class="unix">Solaris</li>
pyquery

The text and html methods

The text method returns the text content of the selected elements, while html returns the inner HTML of the first selected element. The outer_html method includes the element itself.

text_html.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')
items = doc('ul')

print(items.text())
print('-----------------')
print(items.html())
print('-----------------')
print(doc('a').outer_html())

We print the text and the inner HTML of the ul element and the outer HTML of the first link.

print(items.text())

The text method squashes whitespace; text from block elements such as li is placed on separate lines, text from inline elements is joined with spaces.

print(doc('a').outer_html())

The selector matches two links; outer_html (like html) works on the first one.

$ python text_html.py
Solaris
FreeBSD
Debian
NetBSD
Windows
-----------------

        <li class="unix">Solaris</li>
        <li class="bsd">FreeBSD</li>
        <li class="linux">Debian</li>
        <li class="bsd">NetBSD</li>
        <li>Windows</li>
    
-----------------
<a href="https://www.debian.org/">Debian</a>

Attributes

Element attributes are read with the attr method. The attr object also supports attribute access, where reserved words such as class get a trailing underscore.

attributes.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')
ul = doc('ul')

print(ul.attr('id'))
print(ul.attr('style'))
print(ul.attr.class_)

for link in doc('a').items():
    print(link.attr('href'))

print(doc('li:last').attr('class'))

We read the attributes of the ul element and the href attributes of both links.

print(ul.attr.class_)

This is the same as ul.attr('class').

for link in doc('a').items():
    print(link.attr('href'))

Like html, the attr method reads from the first element only. To get an attribute of every match, we iterate over the elements with items.

print(doc('li:last').attr('class'))

A missing attribute is returned as None.

$ python attributes.py
oslist
width:150px
systems
https://www.debian.org/
https://www.freebsd.org/
None

Selecting elements

Selectors find elements by tag name, id, class, attribute, position, or a combination of these. Besides standard CSS selectors, pyquery supports jQuery pseudo-classes such as :first, :last, :odd, :eq, and :contains.

selecting.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')

print(doc('#oslist').attr('class'))
print(doc('li.bsd').text())
print(doc('li[class]').text())
print(doc('li:first').text())
print(doc('li:last').text())
print(doc('li:odd').text())
print(doc('li:eq(2)').text())
print(doc('li:contains("BSD")').text())
print(doc('ul > li:not(.bsd)').text())

The example selects elements with various selectors.

print(doc('#oslist').attr('class'))
print(doc('li.bsd').text())
print(doc('li[class]').text())

We select an element by its id, li elements by class, and li elements that have a class attribute.

print(doc('li:odd').text())
print(doc('li:eq(2)').text())

Positions are zero-based, as in jQuery: :odd matches the second and fourth item, and :eq(2) matches the third one.

print(doc('li:contains("BSD")').text())
print(doc('ul > li:not(.bsd)').text())

The :contains pseudo-class matches elements whose text contains the given string. The last selector picks direct children of ul that do not have the bsd class.

$ python selecting.py
systems
FreeBSD NetBSD
Solaris FreeBSD Debian NetBSD
Solaris
Windows
FreeBSD NetBSD
Debian
FreeBSD NetBSD
Solaris Debian Windows

Iterating with items

Iterating over a PyQuery object directly yields lxml elements. The items method yields each match wrapped in its own PyQuery object, so we can use the pyquery API on it.

iterate.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')

for item in doc('li').items():
    print(item.text(), item.attr('class'))

names = [item.text() for item in doc.items('li')]
print(names)

We print the text and class of every li element and build a list of names.

names = [item.text() for item in doc.items('li')]

The items method also accepts a selector, so doc.items('li') is a shortcut for doc('li').items().

$ python iterate.py
Solaris unix
FreeBSD bsd
Debian linux
NetBSD bsd
Windows None
['Solaris', 'FreeBSD', 'Debian', 'NetBSD', 'Windows']

The each method

The each method calls a function for every element. The function receives the index and the underlying lxml element.

each_elem.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')

def show(idx, el):
    print(f'{idx}: <{el.tag}> {el.text}')

doc('li').each(show)

first = doc('li')[0]
print(type(first))

We print the index, tag name, and text of every li element.

def show(idx, el):
    print(f'{idx}: <{el.tag}> {el.text}')

The el parameter is a plain lxml element, so we use its tag and text attributes rather than pyquery methods.

first = doc('li')[0]

Indexing a PyQuery object also returns an lxml element.

$ python each_elem.py
0: <li> Solaris
1: <li> FreeBSD
2: <li> Debian
3: <li> NetBSD
4: <li> Windows
<class 'lxml.html.HtmlElement'>

Traversing the tree

Traversal methods move from the selected elements to related ones: prev, next, siblings, parent, closest, children, and find. Most of them accept an optional selector that filters the result.

traversing.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')

debian = doc('li.linux')

print(debian.prev().text())
print(debian.next().text())
print(debian.siblings('.bsd').text())
print(debian.parent().attr('id'))
print(debian.closest('body').children('h2').text())

body = doc('body')
print(body.find('a').eq(1).text())
print(body.children().length)

Starting from the Debian item, we visit its neighbours, its parent, and other parts of the document.

print(debian.siblings('.bsd').text())

The siblings method returns all other children of the parent; the selector keeps only those with the bsd class.

print(debian.closest('body').children('h2').text())

The closest method walks up the tree to the first ancestor matching the selector. The children method returns the direct children only.

print(body.find('a').eq(1).text())
print(body.children().length)

The find method searches all descendants. The body element has three children: h2, ul, and p.

$ python traversing.py
FreeBSD
NetBSD
FreeBSD NetBSD
oslist
Operating systems
FreeBSD
3

Filtering elements

The filter method reduces a selection to the elements that match a selector or for which a function returns true. The not_ method does the opposite.

filtering.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')
items = doc('li')

print(items.filter('.bsd').text())
print(items.filter(lambda i: pq(this).text().startswith(('F', 'D'))).text())
print(items.filter(lambda i, el: len(el.text) > 6).text())
print(items.not_('.bsd').text())

We filter the list items in several ways.

print(items.filter(lambda i: pq(this).text().startswith(('F', 'D'))).text())

In jQuery style, a one-parameter function receives the index and the current element is available as this; pyquery injects the name into the function's globals.

print(items.filter(lambda i, el: len(el.text) > 6).text())

A function with two parameters receives the element as the second argument, which avoids the magic this name.

print(items.not_('.bsd').text())

The method is named not_ because not is a Python keyword.

$ python filtering.py
FreeBSD NetBSD
FreeBSD Debian
Solaris FreeBSD Windows
Solaris Debian Windows

The map method

The map method calls a function for every element and collects the return values. None results are dropped.

mapping.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')

lengths = doc('li').map(lambda i, el: len(el.text))
print(list(lengths))

hosts = doc('a').map(lambda i, el: pq(el).attr('href').split('/')[2])
print(list(hosts))

We compute the length of every item name and extract the host names from the links.

hosts = doc('a').map(lambda i, el: pq(el).attr('href').split('/')[2])

We wrap the lxml element in pq to use the attr method. The result is a PyQuery object holding strings; we convert it to a list for printing.

$ python mapping.py
[7, 7, 6, 6, 7]
['www.debian.org', 'www.freebsd.org']

Modifying the document

pyquery can change the document in place. The prepend and append methods insert content at the beginning and the end of an element; add_class, css, text, and remove_attr change classes, styles, text, and attributes.

modifying.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')
items = doc('#oslist')

items.prepend('<li>DragonFly</li>')
items.append('<li>OpenBSD</li>')
doc('li:contains("Windows")').add_class('proprietary').css('color', 'gray')
doc('li.unix').text('illumos')
doc('ul').remove_attr('style')

print(items.outer_html())

We add two items to the list, mark the Windows item, rename the Solaris item, and remove the inline style of the list.

items.prepend('<li>DragonFly</li>')
items.append('<li>OpenBSD</li>')

The inserted HTML string is parsed into new elements.

doc('li:contains("Windows")').add_class('proprietary').css('color', 'gray')

Modifying methods return the same PyQuery object, so they can be chained.

$ python modifying.py
<ul id="oslist" class="systems"><li>DragonFly</li>
        <li class="unix">illumos</li>
        <li class="bsd">FreeBSD</li>
        <li class="linux">Debian</li>
        <li class="bsd">NetBSD</li>
        <li class="proprietary" style="color: gray">Windows</li>
    <li>OpenBSD</li></ul>

Removing elements

The remove method deletes the selected elements from the document and returns them. The empty method removes the content of an element but keeps the element itself.

removing.py
from pyquery import PyQuery as pq

doc = pq(filename='index.html')

removed = doc('li.bsd').remove()
print(removed.length, removed.text())

doc('li:last').remove()
doc('p').empty()

print(doc('ul').outer_html())
print(doc('p').outer_html())

We remove the BSD items and the last item from the list, and empty the paragraph.

removed = doc('li.bsd').remove()
print(removed.length, removed.text())

The removed elements are still available through the returned object.

doc('li:last').remove()

After the BSD items are gone, the last item is Windows.

The whitespace text around the removed elements stays in the document, which is why the output contains empty lines.

$ python removing.py
2 FreeBSD NetBSD
<ul id="oslist" class="systems" style="width:150px">
        <li class="unix">Solaris</li>
        
        <li class="linux">Debian</li>
        
        
    </ul>
<p></p>

Querying XML

Without the parser argument, pyquery tries the XML parser first and falls back to the HTML parser, but it translates selectors in HTML mode, which lowercases element names. For XML documents with mixed-case names we pass parser='xml'. The following RSS feed is used in the next example.

rss.xml
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  <channel>
    <title>Release notes</title>
    <item>
      <title>Debian 13 released</title>
      <pubDate>Sat, 09 Aug 2025 10:00:00 GMT</pubDate>
    </item>
    <item>
      <title>FreeBSD 15.0 released</title>
      <pubDate>Tue, 02 Dec 2025 09:00:00 GMT</pubDate>
    </item>
  </channel>
</rss>

The feed contains a channel title and two items.

read_xml.py
from pyquery import PyQuery as pq

doc = pq(filename='rss.xml', parser='xml')

print(doc('channel > title').text())

for item in doc('item').items():
    print(item('title').text(), '|', item('pubDate').text())

We print the channel title and the title and date of every item.

doc = pq(filename='rss.xml', parser='xml')

With parser='xml', both the document and the selectors keep their case, so the pubDate selector matches. Without the argument, the selector would be lowercased to pubdate and find nothing.

print(doc('channel > title').text())

The child combinator excludes the title elements of the items.

$ python read_xml.py
Release notes
Debian 13 released | Sat, 09 Aug 2025 10:00:00 GMT
FreeBSD 15.0 released | Tue, 02 Dec 2025 09:00:00 GMT

Web scraping

pyquery can download a page itself with the url keyword, but using an HTTP library such as requests gives us control over timeouts, headers, and error handling.

scraping.py
from pyquery import PyQuery as pq
import requests

resp = requests.get('https://example.com', timeout=10)
resp.raise_for_status()

doc = pq(resp.text)

print(doc('title').text())
print(doc('p').eq(0).text())

The example downloads the example.com page and prints its title and the first paragraph.

resp = requests.get('https://example.com', timeout=10)
resp.raise_for_status()

We fetch the page and raise an exception for HTTP error codes.

doc = pq(resp.text)

The HTML text of the response is parsed into a PyQuery object.

The output depends on the live page and may change over time.

$ python scraping.py
Example Domain
This domain is for use in documentation examples without needing permission. This is not a service; avoid relying on it for testing and monitoring purposes.

Source

pyquery documentation

jQuery selectors

In this article we have queried and modified HTML and XML documents with the Python pyquery library. See also Python lxml, Python BeautifulSoup, and Python web scraping.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.