Reputation: 525
I'm checking sports stats, but quite often there's no red cards, and so it comes back as a noneType
error and it's quite an important stat so I can't just skip it. I'd like to be able to print "Red Cards" as "0" if the team got no red cards.
import requests
import re
import csv
from bs4 import BeautifulSoup
row = soup.select_one('.statRow:has(*:contains("Red Cards"))')
home_value12 = row.select_one('.statText--homeValue').text
away_value12 = row.select_one('.statText--awayValue').text
I had figured on using an if statement, but I can't seem to get it right - it either ignores the if statement or throws an error. I know there's ways to skip noneType
errors, but I'd sooner not skip it, but count it as zero.
Thanks for your help on this one.
Upvotes: 2
Views: 37
Reputation: 4101
Try the following
import requests
import re
import csv
from bs4 import BeautifulSoup
row = soup.select_one('.statRow:has(*:contains("Red Cards"))')
try:
home_value12 = row.select_one('.statText--homeValue').text
away_value12 = row.select_one('.statText--awayValue').text
except AttributeError:
home_value12 = 0
away_value12 = 0
if home_value12 is not None:
print(home_value12)
else:
print(0)
Upvotes: 1