3eee3
3eee3

Reputation: 155

Search by tag contents with BeautifulSoup

I would like to search for a particular tag by it's text contents. For example:

<a href="http://goinghere.com">Lets go somewhere</a>

I want to find the above by searching for the text 'Lets go somewhere'. I am currently doing it using re. Can it be done in BeautifulSoup or is it better to use re in this case?

Upvotes: 2

Views: 2943

Answers (1)

kungphu
kungphu

Reputation: 4859

s = BeautifulSoup(...)
s.find(text='Lets go somewhere')

You can also use regex.

Using BeautifulSoup to find a HTML tag that contains certain text

Edit: While the find method prints a string if you use it on the command line, that's actually just a representation of the object it returns; you can access the parent attribute on it to access its BeautifulSoup tag object.

Upvotes: 2

Related Questions