BS4 - "AttributeError: 'NoneType' object has no attribute 'text'"



我无法使用 bs4 从此网页中提取数据,收到以下错误

"AttributeError: 'NoneType' object has no attribute 'text'"

有人可以修改我的代码吗?

这是我的代码

from bs4 import BeautifulSoup
import requests
url = 'https://e-masjid.jais.gov.my/index.php/profail?page=1'
html_content = requests.get(url).text
soup = BeautifulSoup(html_content, 'lxml')
masjid_table = soup.find("table", attrs={"class": "Masjid"})
masjid_table_data = masjid_table.tbody.find_all("tr")
headings = []
for td in masjid_table_data[0].find_all("td"):
headings.append(td.b.text.replace('n', ' ').strip())
print(headings)masjid_table = soup.find("table", attrs={"class": "Masjid"})
masjid_table_data = masjid_table.tbody.find_all("tr")
headings = []
for td in masjid_table_data[0].find_all("td"):
headings.append(td.b.text.replace('n', ' ').strip())
print(headings)

虽然我不知道你想要的输出是什么。这将为你得到所有的清真寺名称。

soup = BeautifulSoup(html_content.text, 'lxml')
masjid_table = soup.find("table", attrs={"id": "pemohon"})
masjid_table_data = masjid_table.tbody.find_all("tr")
headings = []
for row in masjid_table_data:
headings.append(row.find_all('td')[1].text.replace('nMASJID', ' ').strip())

您可以尝试在此处更改索引row.find_all('td')[1]以获取相应的列。

属性错误意味着您正在调用给定对象不存在的属性。 在您的情况下,requests.get(url)返回 None,因此requests.get(url).textNone.text相同,这是无效的。 如果这是预期的,请检查请求是否返回某些内容:

result = requests.get(url)
if result:
string = requests.get(url).text

相关内容

最新更新