Storing data from a tag in Python with BeautifulSoup4
<p>Using BeautifulSoup4, I can isolate:
</p>

<pre><code>&lt;a href="#" data-nutrition="{
    &amp;quot;serving-name&amp;quot;:&amp;quot;Milk, 2%&amp;quot;,
    &amp;quot;serving-size&amp;quot;:&amp;quot;16 FL OZ&amp;quot;,
    &amp;quot;calories&amp;quot;:&amp;quot;267&amp;quot;}"&gt;
Milk, 2%
&lt;i class="icon-leaf icon-hidden-text"&gt;Meatless&lt;/i&gt;
&lt;/a&gt;
</code></pre>

<p>By running:
</p>

<pre><code>for i in soup('a', attrs={'data-nutrition' : True}):
    sample = i
    break
print(sample)
</code></pre>

<p>I need create the dictionary:
</p>

<pre><code>my_dict = {
    'serving-name': 'Milk, 2%',
    'serving-size': '16 FL OZ',
    'calories': '267'
}
</code></pre>

<p>How can I do this using BeautifulSoup4 in Python?</p>

<p>Locate the element and use <a href="https://docs.python.org/2/library/json.html#json.loads" rel="nofollow"><code>json.loads()</code></a> to load the <code>data-nutrition</code> attribute value into the Python dictionary:</p>

<pre><code>import json
from bs4 import BeautifulSoup


data = """
&lt;a href="#" data-nutrition="{
    &amp;quot;serving-name&amp;quot;:&amp;quot;Milk, 2%&amp;quot;,
    &amp;quot;serving-size&amp;quot;:&amp;quot;16 FL OZ&amp;quot;,
    &amp;quot;calories&amp;quot;:&amp;quot;267&amp;quot;}"&gt;
Milk, 2%
&lt;i class="icon-leaf icon-hidden-text"&gt;Meatless&lt;/i&gt;
&lt;/a&gt;"""
soup = BeautifulSoup(data, "html.parser")

a = soup.select_one("a[data-nutrition]")
nutrition = json.loads(a["data-nutrition"])
print(nutrition)
</code></pre>

<p>Prints:</p>

<pre><code>{'serving-name': 'Milk, 2%', 'serving-size': '16 FL OZ', 'calories': '267'}
</code></pre>

python beautifulsoup