在不同情况下格式化不同时使用 Beautiful Soup 抓取数据

Scrape data with Beautiful Soup when its formatted differently in different situations

我正试图从网络上抓取州长选举数据,但我正在努力处理其中的一部分。因此,正如您在这两种情况下看到的那样,要么有两名候选人(民主党或共和党),要么有 3 名候选人(民主党、共和党、独立党)。

我写了下面的代码来抓取数据。这适用于 2 种候选情况,但我不确定如何让它适用于这两种情况。

这是我的代码:

html = requests.get(url).text

soup = BeautifulSoup(html, 'html.parser')

#Scrape the percentage Numbers
table = soup.find_all('table')[0]
table_row = table.find_all('tr')[1]
table_data = table_row.find_all('td')[3:5]

案例 1:

案例 2:

html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
table = soup.find_all('table')[0]
table_row = table.find_all('tr')[1]
table_data = table_row.find_all('td')
if table_data[-1].class == 'spread': #checking whether the last td has class spread
    table_data = table_data[3:5]
else: 
    table_data = table_data[3:6]