#python #python-3.x #beautifulsoup
#python #python-3.x #beautifulsoup
Вопрос:
Я пытаюсь перебрать все заголовки столбцов строки [0], затем удалите символ Юникода и номер ссылки после названия планеты. Прямо сейчас мой код выглядит так:-
URL_solar_system = "https://en.wikipedia.org/wiki/List_of_gravitationally_rounded_objects_of_the_Solar_System"
from bs4 import BeautifulSoup
import requests
html_content = requests.get(URL_solar_system).text
soup_solar = BeautifulSoup(html_content, "lxml")
tables = soup_solar.find_all('table', attrs={'class': 'wikitable'})
planets = tables[2]
rows = planets.find_all('tr')
headers = [th.text.strip() for th in rows[0].find_all('th') if th.get_text().strip() != '' ]
print('headers: {}'.format(headers))
ВЫВОД
headers: ['*Mercury[6][7]', '*Venus[8][9]', '*Earth[10][11]', '*Mars[12][13]', '°Jupiter[14][15]', '°Saturn[16][17]', '‡Uranus[18][19]', '‡Neptune[20][21]']
Я пытаюсь получить результат, как показано ниже.
Желаемый результат:
headers: ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
Подсказка для написания кода:-
- заголовки = []
- цикл for, который будет проходить через строку [0] с поиском всех на ‘th’
- first_variable = использует ваш итератор (допустим, мы назовем его i в определении цикла for) и использует для него метод text
- second_variable = найдите это значение ‘[‘ из первой переменной, имеющей метод text переопределите первую переменную, индексируя второй элемент на второй переменный элемент, который вы определили.
- оператор if для этой метки where is добавляет первую переменную в созданный вами список заголовков.
Ответ №1:
Добавить
import re # in the begining of your module
затем просто добавьте в конец вашего кода следующую строку
headers = re.findall(r'(w )[d ]',''.join(headers))
Ваш окончательный код
import re
URL_solar_system = "https://en.wikipedia.org/wiki/List_of_gravitationally_rounded_objects_of_the_Solar_System"
from bs4 import BeautifulSoup
import requests
html_content = requests.get(URL_solar_system).text
soup_solar = BeautifulSoup(html_content, "lxml")
tables = soup_solar.find_all('table', attrs={'class': 'wikitable'})
planets = tables[2]
rows = planets.find_all('tr')
headers = [th.text.strip() for th in rows[0].find_all('th') if th.get_text().strip() != '' ]
headers = re.findall(r'(w )[d ]',''.join(headers))
print('headers: {}'.format(headers))
Комментарии:
1. Я изменил anser там, где нам нужно
import re
, в начале вашего modue, чтобы использовать обычное выражение.
Ответ №2:
Текст заголовка находится href
под четвертой таблицей. Попробуйте использовать селектор CSS, который выбирает четвертую таблицу: table:nth-of-type(4)
, а затем использует th > a
, который выбирает a
теги (заголовки) под th
тегами.
import requests
from bs4 import BeautifulSoup
URL = "https://en.wikipedia.org/wiki/List_of_gravitationally_rounded_objects_of_the_Solar_System"
soup = BeautifulSoup(requests.get(URL).content, "html.parser")
print([tag.text for tag in soup.select("table:nth-of-type(4) th > a")])
Вывод:
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']