🚀 We are hiring! See open positions

How to use CSS Selectors in Python?

by scrapecrow Oct 31, 2022

Python has several popular packages that can parse HTML using CSS selectors.
The most popular one is BeautifulSoup which can execute CSS selectors through the select() and select_one() methods:

from bs4 import BeautifulSoup

soup = BeautifulSoup("""
<a>link 1</a>
<a>link 2</a>
""")

print(soup.select_one('a'))
"<a>link 1</a>"
print(soup.select('a'))
["<a>link 1</a>", "<a>link 2</a>"]

Another popular package is parsel (also used by scrapy) which can execute CSS selectors through the css() method:

from parsel import Selector

soup = Selector("""
<a>link 1</a>
<a>link 2</a>
""")

print(soup.css('a').get())
"<a>link 1</a>"
print(soup.css('a').getall())
["<a>link 1</a>", "<a>link 2</a>"]

Related Articles

How to Parse XML

In this article, we'll explain about XML parsing. We'll start by defining XML files, their format and how to navigate them for data extraction.

PYTHON
CSS-SELECTORS
XPATH
DATA-PARSING
How to Parse XML

How to Scrape Imovelweb.com

Scrape Imovelweb with Python - extract listings and details, handle pagination and JSON-LD, and use Scrapfly for anti-bot reliability.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
SCRAPFLY
How to Scrape Imovelweb.com

How to Scrape AutoScout24

Learn how to scrape AutoScout24 for car listings, prices, specifications, and detailed vehicle information using Python. Complete guide with code examples and anti-blocking techniques.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape AutoScout24

How to Scrape Allegro.pl

Learn how to scrape Allegro.pl for product listings and individual product details using Python with requests and BeautifulSoup4

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape Allegro.pl

How to Scrape Ticketmaster

Learn how to scrape Ticketmaster for event data including concerts, venues, dates, and ticket information using Python. Complete guide with code examples and anti-blocking techniques.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape Ticketmaster

How to Scrape Mouser.com

Learn how to scrape Mouser.com electronic component data including prices, specifications, and inventory using Python. Complete guide with code examples and anti-blocking techniques.

PYTHON
SCRAPEGUIDE
BEAUTIFULSOUP
REQUESTS
How to Scrape Mouser.com