Biggen Biggen -4 years ago 85
Python Question

Filter href out of selector

I have these piece of code:

record = game.select_one('td:nth-of-type(4)')


Depending on the page I run that on, I get either a link between that specific
td
tag or just text. For example I don't want any links like below:

<td><a href="https://www.uselesslink.com">Useless link text</a></td>


But I do need:

<td>Here is some juicy text</td>


I need to be able to filter the link so that if a link is found, I can just print "None". So something like this:

if record has link:
print('Nothing to show')
else:
print('text found')


There must be an easy way to test for
href
or an
a
tag but I can't seem to nail it down.

Answer Source

You can simply check if a is found this way:

if record.a is not None:  # link found

record.a is a shortcut to record.find("a"), .find() method returns None if an element is not found.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download