🚀 We are hiring! See open positions

How to find HTML elements by attribute using BeautifulSoup?

Using Python and BeautifulSoup, to find elements by attribute value we can use find and find_all methods or CSS selectors through the select and select_one methods:

python
import bs4
soup = bs4.BeautifulSoup('<a alt="this is a link">some link</a>')

# to find exact matches:
soup.find("a", alt="this is a link")
# or
soup.find("a", {"alt": "this is a link"})

# to find partial matches we can use regular expressions:
import re
soup.find("a", alt=re.compile("a link", re.I))  # tip: the re.I paramter makes this case insensitive

# or using CSS selectors for exact matches:
soup.select('a[alt="this is a link"]')
# and to find partial matches we can contains matcher `*=`:
soup.select('a[alt*="a link"]')
# or
soup.select('a[alt*="a link" i]')  # tip: the "i" suffix makes this case insensitive
Scale Your Web Scraping
Anti-bot bypass, browser rendering, and rotating proxies — all in one API. Start with 1,000 free credits.
No credit card required 1,000 free API credits Anti-bot bypass included
Not ready? Get our newsletter instead.