Hatshepsut
Hatshepsut

Reputation: 6632

Get tag's attribute if tag exists; otherwise None

I have a td tag in BeautifulSoup 4. There may be an a tag inside it:

row.find_all('td')[2].find('a')

If there is, I want to retrieve the a tag's href attribute. Otherwise, I'd like None.

This is what I've thought of:

getattr(row.find_all('td')[2].find('a'), 'attrs', {}).get('href')

What's an efficient way to do this?

Example row:

<tr><td><a href="http://google.com">405</a></td>
\n<td><font face="Arial" size="-1">12-Jul</font></td>\n<td><font face="Arial" size="-1">There could be an a-tag here.</fo
nt></td>\n<td><font face="Arial" size="-1">On Motion</font></td>\n<td align="CENTER"><fo
nt face="Arial" size="-1">F</font></td>\n<td><font face="Arial" size="-1">\xa0</font></td></tr> 

Upvotes: 0

Views: 1528

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can select the second tr and any anchor inside then check using an if:

a = soup.select_one("tr:nth-of-type(2) a[href]")


if a:
    print(a["href"])

If there is no anchor a will be None, if there is you can just extract the href.

Upvotes: 1

Related Questions