Issue
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**
Solution
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 )
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.