Несколько имен классов для таблицы

#python #beautifulsoup

#python #beautifulsoup

Вопрос:

Я пытаюсь использовать BeautifulSoup для очистки этой веб-страницы:https://en.wikipedia.org/wiki/List_of_countries_by_GDP_sector_composition

 import requests
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_sector_composition#GDP_from_natural_resources"
response = requests.get(url)
wiki_soup = BeautifulSoup(response.text, "html")

right_table= wiki_soup.find('table', class_="wikitable sortable")
right_table
  

Я хочу взять таблицу под названием «ВВП от природных ресурсов», но все таблицы здесь имеют то же имя класса, что и «сортируемый для викификации». Как мне указать именно эту таблицу?

Спасибо!

Комментарии:

1. Вероятно, вам потребуется выполнить поиск по тексту заголовка таблицы (например: структура сектора ВВП (ППС))

Ответ №1:

Вы могли бы найти таблицу, просмотрев раздел id (GDP_from_natural_resources), а затем захватить первую таблицу :

 import requests
from bs4 import BeautifulSoup

url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_sector_composition#GDP_from_natural_resources"
response = requests.get(url)
wiki_soup = BeautifulSoup(response.text, "html")

right_table = wiki_soup.find('span', {'id':'GDP_from_natural_resources'}).find_parent('h2').findNext('table')
  

Вывод:

 |     | Country/Economy                |   Total natural resources (% of GDP) | Oil (% of GDP)   | Natural gas (% of GDP)   | Coal (% of GDP)   |   Mineral (% of GDP) | Forest (% of GDP)   |
|----:|:-------------------------------|-------------------------------------:|:-----------------|:-------------------------|:------------------|---------------------:|:--------------------|
|   0 | Afghanistan                    |                                  2.1 | ..               | ..                       | 0                 |                  0   | 2.1                 |
|   1 | Albania                        |                                  5.1 | 4.6              | 0                        | 0                 |                  0.5 | 0.1                 |
|   2 | Algeria                        |                                 26.3 | 19               | 7                        | 0                 |                  0.3 | 0.1                 |
|   3 | Angola                         |                                 46.6 | 46.3             | 0.1                      | ..                |                  0   | 0.2                 |
|   4 | Antigua and Barbuda            |                                  0   | ..               | ..                       | ..                |                  0   | ..                  |
  

Комментарии:

1. Мне больше нравится это решение. Если в вики будет обновлено больше таблиц, которые появятся перед нужной вам таблицей, скрипт продолжит работу.

Ответ №2:

Вы можете использовать селектор CSS table:nth-of-type(5) :

 import requests
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_sector_composition#GDP_from_natural_resources"
response = requests.get(url)
wiki_soup = BeautifulSoup(response.text, "html.parser")

right_table = wiki_soup.select_one('table:nth-of-type(5)')

for row in right_table.select('tr'):
    data = [td.get_text(strip=True) for td in row.select('td')]
    print(' '.join('{: <25}'.format(d) for d in data))
  

Вывод:

 Afghanistan               2.1                       ..                        ..                        0                         0                         2.1                      
Albania                   5.1                       4.6                       0                         0                         0.5                       0.1                      
Algeria                   26.3                      19                        7                         0                         0.3                       0.1                      
Angola                    46.6                      46.3                      0.1                       ..                        0                         0.2                      
Antigua and Barbuda       0                         ..                        ..                        ..                        0                         ..                       
Argentina                 6.1                       4.1                       1.2                       0                         0.8                       0.1                      
Armenia                   2.7                       ..                        ..                        ..                        2.7                       0                        
Australia                 10.7                      0.8                       0.7                       1.9                       7.2                       0.1                      
Austria                   0.4                       0.1                       0                         0                         0.1                       0.1                      
Azerbaijan                45.1                      41.9                      3.1                       ..                        0.1                       0                        
Bahamas, The              0                         ..                        ..                        ..                        0                         0                        
Bangladesh                3.4                       ..                        2.8                       0.1                       0                         0.5                      
Barbados                  0                         ..                        ..                        ..                        0                         ..                       
Belarus                   2.4                       1.8                       0                         ..                        0                         0.5                      
Belgium                   0                         ..                        ..                        0                         0                         0                        
Belize                    0.3                       ..                        ..                        ..                        0                         0.3                      
Benin                     1.7                       ..                        ..                        ..                        0                         1.6                      
Bhutan                    8.4                       ..                        ..                        0                         0                         8.4                      
Bolivia                   20.6                      5.4                       8.6                       ..                        6.3                       0.3     
...
...
...