【问题标题】:BS4 - "AttributeError: 'NoneType' object has no attribute 'text'"BS4 - “AttributeError: 'NoneType' 对象没有属性 'text'”
【发布时间】:2020-06-19 03:38:16
【问题描述】:

由于出现以下错误,我无法使用 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)

【问题讨论】:

  • 你想提取什么,你能添加一些示例输出吗?
  • 尝试打印(汤),结果如何。
  • 你可以在这里查看输出pastebin.com/nrhL7RPB

标签: python beautifulsoup


【解决方案1】:

虽然我不知道您想要的输出是什么.. 这将为您提供所有的 masjid 名称..

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] 以获取相应的列。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 2021-03-24
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多