1

How i can assign html code to a variable so later I could refer to it?

Example:

"div class='test'" - some html code



some_variable = "'div', {'class': ='test'}" *#assigning above to the variable*

print(soup.find(some_variable)) *# is not working*
print(soup.find('div', {"class": 'test'}) # **is working**

1 Answer 1

3

You can store your search parameters inside dictionary and then use **:

from bs4 import BeautifulSoup


html_doc = '''
<div class="test">This I want</div>
<div class="other">This I dont want</div>
'''

soup = BeautifulSoup(html_doc, 'html.parser')

params = {'name': 'div', 'attrs': {'class': 'test'}}
    
print( soup.find(**params).text )

Prints:

This I want

Or: Use CSS selector:

selector = 'div.test'

print( soup.select_one(selector).text )
Sign up to request clarification or add additional context in comments.

3 Comments

wow, thanks! good to see 2 solutions, but i think i ll stick to selector as it is more clearly for person who reads :P
@zarize, for reference, the **params syntax is called "parameter unpacking", and it essentially "unpacks" the dict params into the keyword parameters of the soup.find function.
Thanks for explanation! I just wonder now... what if i would like to add .text method at the end of the selector? selector = 'div.test'.text wouldnt work of course but i would like to keep possibility to add dynamic method, how to achieve it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.