CSS locators are one of the two types of selectors that Scrapy supports (the other being XPath selectors). CSS selectors use a syntax similar to CSS (Cascading Style Sheets) to select elements from HTML or XML documents.
Here are some examples of CSS selectors:
div elements: divexample: .exampleexample: #examplea element inside a div element: div a:first-of-typep elements with class name important inside a div element with class name content: div.content p.importantCSS selectors are generally shorter and more readable than XPath selectors, especially for simple selections. However, they can be less powerful and flexible than XPath selectors for more complex selections.
To use CSS selectors in Scrapy, you can use the css() method of the Selector or SelectorList object, like this:
from scrapy import Selectorselector = Selector(text='<div class="example"><p>Hello, world!</p></div>')# Select the text content of the first p element inside a div with class name exampletext = selector.css('div.example p:first-of-type::text').get()print(text) # Output: 'Hello, world!' |
In this example, we use the css() method to select the text content of the first p element inside a div element with class name example. The ::text pseudo-element is used to select the text content of the element, rather than the element itself.