Beautiful Soup - Python
<p>I was hoping to ask a pretty simple question. I have come across the below code and have not been able to find a decent explanation as to:</p>

<ol>
<li>What exactly does the <code>.attrs</code> function do in this case?</li>
<li>What is the function of the <code>['href']</code> part at the end i.e. what exactly does that part of the code execute?</li>
</ol>

<p>Here is the code:</p>

<pre><code>from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("url")
bsObj = BeautifulSoup(html)
for link in bsObj.findAll("a"):
    if 'href' in link.attrs:
    print (link.attrs['href']) 
</code></pre>

<p>Let's try to fetch this question it self and see:</p>

<pre><code>from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://stackoverflow.com/q/39308028/1005215")
bsObj = BeautifulSoup(html)
</code></pre>

<blockquote>
  <p>i) what exactly does the .attrs function do in this code</p>
</blockquote>

<pre><code>In [6]: bsObj.findAll("a")[30]
Out[6]: &lt;a class="question-hyperlink" href="/questions/39308028/beautifuelsoup-python"&gt;Beautifuelsoup - Python&lt;/a&gt;

In [7]: bsObj.findAll("a")[30].attrs
Out[7]: 
{'class': ['question-hyperlink'],
 'href': '/questions/39308028/beautifuelsoup-python'}

In [8]: type(bsObj.findAll("a")[30])
Out[8]: bs4.element.Tag
</code></pre>

<p>If you read the <a href="http://beautiful-soup-4.readthedocs.io/en/latest/index.html?highlight=attrs#attributes" rel="nofollow">documentation</a>, you will notice that a tag may have any number of attributes. In the element number 30, the tag has attributes 'class' and 'href'</p>

<blockquote>
  <p>ii) what is the function of the ['href'] part at the end</p>
</blockquote>

<pre><code>In [9]: bsObj.findAll("a")[30]['href']
Out[9]: '/questions/39308028/beautifuelsoup-python'
</code></pre>

<p>If you look at the above output, you will see that the tag had an attribute 'href' and the above code fetched us the value for that attribute.</p>

python