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:

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

Provided by Scrapfly

This knowledgebase is provided by Scrapfly data APIs, check us out! 👇