Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当数据在不同情况下的格式不同时,使用Beautiful Soup刮取数据_Python_Screen Scraping - Fatal编程技术网

Python 当数据在不同情况下的格式不同时,使用Beautiful Soup刮取数据

Python 当数据在不同情况下的格式不同时,使用Beautiful Soup刮取数据,python,screen-scraping,Python,Screen Scraping,我正试图从网络上搜集州长选举数据,其中一部分我正在苦苦挣扎。因此,正如你在这两个案例中所看到的,有两个候选人(民主党或共和党)或三个候选人(民主党、共和党、独立党) 我编写了以下代码来收集数据。这适用于2个候选情况,但我不确定如何使其适用于这两种情况 这是我的密码: html = requests.get(url).text soup = BeautifulSoup(html, 'html.parser') #Scrape the percentage Numbers table = sou

我正试图从网络上搜集州长选举数据,其中一部分我正在苦苦挣扎。因此,正如你在这两个案例中所看到的,有两个候选人(民主党或共和党)或三个候选人(民主党、共和党、独立党)

我编写了以下代码来收集数据。这适用于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:


请把问题弄清楚,你想要什么样的结果。td with class spread包含什么内容。您希望在哪种情况下忽略它。目前,我的代码在案例1中工作,因为它从[3:5]中查找td,但是在第二种情况下,我需要[3:6]。我不知道如何编写一段代码,让我在这两种情况下都能勉强应付。我惊讶地发现,beautifulsoup不能做像
td:not(.spread)
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]