T
T
TechNOIR2018-02-09 10:38:03
Python
TechNOIR, 2018-02-09 10:38:03

Python+BeautifulSoup. Is it possible to search using regular expressions?

Good afternoon.
I'm studying BS4. Can you please tell me if it is possible to search for an element using regular expressions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2020-05-09
@TechNOIR

If you pass in an object with a regular expression, Beautiful Soup will filter the results according to that regular expression using its search() method. The following code finds all tags whose names start with the letter "b"; in our case, these are the body and b tags:

import re
for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
# body
# b

This code finds all tags whose names contain the letter "t":
for tag in soup.find_all(re.compile("t")):
    print(tag.name)
# html
# title

Filter types

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question