Select a tag inside a class with bs4
<p>I'm trying to get the href of this part of html:</p>

<pre><code>&lt;h3 class="post-title entry-title" itemprop="name"&gt;
&lt;a href="http://sslproxies24.blogspot.it/2016/10/01-10-16-free-ssl-proxies-1070.html"&gt;01-10-16 | Free SSL Proxies (1070)&lt;/a&gt;
&lt;/h3&gt;
</code></pre>

<p>So I created this script:</p>

<pre><code>import urllib.request
from bs4 import BeautifulSoup

url = "http://sslproxies24.blogspot.it/"
soup = BeautifulSoup(urllib.request.urlopen(url))
for tag in soup.find_all("h3", "post-title entry-title"):
    links = tag.get("href")
</code></pre>

<p>But links, doesn't find anything. This is because, the class "post-title entry-title" that I selected with bs4, has not attribute "href"...</p>

<p>In fact the output of:</p>

<pre><code>print (tag.attrs)
</code></pre>

<p>is:</p>

<pre><code>{'itemprop': 'name', 'class': ['post-title', 'entry-title']}
</code></pre>

<p>How can I do to select the "a" element and get the links in href?</p>

<p>You can quickly solve it by getting the inner <code>a</code> element:</p>

<pre><code>for tag in soup.find_all("h3", "post-title entry-title"):
    link = tag.a.get("href")
</code></pre>

<p>where <code>tag.a</code> is a shortcut to <code>tag.find("a")</code>.</p>

<p>Or, you can match the <code>a</code> element directly with a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a>:</p>

<pre><code>for a in soup.select("h3.post-title.entry-title &gt; a"):
    link = a.get("href")
</code></pre>

<p>where dot is a <em>class</em> attribute selector, <code>&gt;</code> means <em>direct parent-child relationship</em>.</p>

<p>Or, you can check <code>itemprop</code> attribute instead of a class:</p>

<pre><code>for a in soup.select("h3[itemprop=name] &gt; a"):
    link = a.get("href")
</code></pre>

python python-3.x beautifulsoup bs4