Querying data with XPath and CSS selectors
CSS selectors are patterns used for selectingelements and are often used to define the elements that styles should be applied to. They can also be used with lxml to select nodes in the DOM. CSS selectors are commonly used as they are more compact than XPath and generally can be more reusable in code. Examples of common selectors which may be used are as follows:
What you are looking for | Example |
All tags |
|
A specific tag (that is, |
|
A class name (that is, |
|
A tag with an |
|
A child |
|
A descendant |
|
A tag with an attribute (that is, |
|
Getting ready
Let's start examining CSS selectors using the same start up code we used in the last recipe. These code snippets are also in the 02/04_css_selectors.py
.
In [1]: from lxml import html ...: import requests ...: page_html = requests.get("http://localhost:8080/planets.html").text ...: tree = html...