Объект 'NoneType' не имеет атрибута 'text' BeautifulSoup Python - PullRequest
0 голосов
/ 03 августа 2020

Я пытаюсь сканировать данные с указанного ниже URL-адреса, но получаю AttributeError: 'NoneType' object has no attribute 'text'

Как мне сканировать веб-сайт, чтобы он проходил через каждый td и получал двуязычный текст?

Вот что у меня есть

from bs4 import BeautifulSoup
import requests

url="http://www.mongols.eu/mongolian-language/mongolian-tale-six-silver-stars/"

html_content = requests.get(url).text

# Parse the html content
soup = BeautifulSoup(html_content, "lxml")

gdp_table = soup.find("table", attrs={"class": "table-translations"})
gdp_table_data = gdp_table.tbody.find_all("tr")  # contains # rows

# Get all the headings of Lists
headings = []
for td in gdp_table_data[0].find_all("td"):
    # remove any newlines and extra spaces from left and right
    headings.append(td.b.text.replace('\n', ' ').strip())

print(headings)

Ответы [ 2 ]

0 голосов
/ 03 августа 2020

В этой строке headings.append(td.b.text.replace('\n', ' ').strip()), поскольку в столбце таблицы нет атрибута b, программа выдает ошибку.

Более того, вам не нужно анализировать strong текст отдельно, используйте td.text вместо этого.

from bs4 import BeautifulSoup
import requests

url="http://www.mongols.eu/mongolian-language/mongolian-tale-six-silver-stars/"

html_content = requests.get(url).text

# Parse the html content
soup = BeautifulSoup(html_content, "lxml")

gdp_table = soup.find("table", attrs={"class": "table-translations"})
gdp_table_data = gdp_table.tbody.find_all("tr")  # contains # rows
print(gdp_table_data[0].find_all("td"))
# Get all the headings of Lists
headings = []
for td in gdp_table_data[0].find_all("td"):
    # remove any newlines and extra spaces from left and right and append to headings
    headings.append(td.get_text(strip=True))
print(headings)
# output ['No.', 'Mongolian text', 'Loosely translated into English']
0 голосов
/ 03 августа 2020

вы сохранили td.b внутри для l oop, что дает ошибку, потому что в таблице нет ничего с атрибутом 'b'. Удалив его, вы можете получить результат.

from bs4 import BeautifulSoup
import requests

url="http://www.mongols.eu/mongolian-language/mongolian-tale-six-silver-stars/"

html_content = requests.get(url).text
# Parse the html content
soup = BeautifulSoup(html_content, "lxml")

gdp_table = soup.find("table", attrs={"class": "table-translations"})
gdp_table_data = gdp_table.tbody.find_all("tr")  # contains # rows

# Get all the headings of Lists
headings = []
for td in gdp_table_data[0].find_all("td"):
    # remove any newlines and extra spaces from left and right
    headings.append(td.text.replace('\n', ' ').strip())

print(headings)

Вот результат, который я получил

['No.', 'Mongolian text', 'Loosely translated into English']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...