AttributeError:“NoneType”对象没有属性“tbody”Spyder 3.3.1/beautifulsoup4/python 3.6

2024-04-26 21:10:26 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,这是我的设置:Spyder 3.3.1/beauthoulsoup4/python3.6

下面的代码来自一篇关于medium(here)的文章,内容是关于使用python和Beautifulsoup进行web清理。本来应该是一个快速阅读,但现在两天后,我仍然无法让代码在spyder中运行并继续获取:

File "/Users/xxxxxxx/Documents/testdir/swiftScrape.py", line 9, in table_to_df
    return pd.DataFrame([[td.text for td in row.findAll('td')] for row in table.tbody.findAll('tr')])

AttributeError: 'NoneType' object has no attribute 'tbody'

不确定出了什么问题,似乎是一个实现错误。有谁能帮忙解释一下这个问题吗。在

提前谢谢。在

^{pr2}$

Tags: 代码in内容forhere文章tabletd
2条回答

就像在web上找到的一个丢失的示例代码一样,这段代码不是产品级代码—它盲目地假设http请求总是成功的并返回预期的内容。事实上,通常情况并非如此(网络错误、代理或防火墙阻止您,站点关闭—暂时或肯定,站点更新更改了URL和/或页面标记等)。在

你的问题表现在:

def table_to_df(table):
    return pd.DataFrame([[td.text for td in row.findAll('td')] for row in table.tbody.findAll('tr')])

来自table实际上是None,这意味着在for循环中:

^{pr2}$

在html文档中找不到id为“tableID”的“table”标记。您可以通过打印实际的html内容来检查:

while True:
    print(counter)
    page = requests.get(url)
    soup = bs4.BeautifulSoup(page.content, 'lxml')
    table = soup.find(name='table', attrs={'id':'tableID'})
    if table is None:
        print("no table 'tableID' found for url {}".format(url))
        print("html content:\n{}\n".format( page.content))
        continye

    # etc

感谢@bruno deshuilliers的指点。非常感谢。在

这是我使用Selenium和webdriver而不是import requests重写的代码:

import os
import bs4
import pandas as pd
from selenium import webdriver

PATH = os.path.join('/','Users','benmorris','documents','testdir')

def table_to_df(table):
    return pd.DataFrame([[td.text for td in row.find_all('td')] for row in soup.find_all('tr')])

def next_page(soup):
    return "http:" + soup.find('a', attrs={'rel':'next'}).get('href')

res = pd.DataFrame()
url = "http://bank-code.net/country/FRANCE-%28FR%29/"
counter = 0
driver = webdriver.Chrome()
driver.get(url)

while True:
    print(counter)
    page = driver.get(url)
    soup = bs4.BeautifulSoup(driver.page_source, 'lxml')
    table = driver.find_element_by_xpath('//*[@id="tableID"]')
    if table is None:
        print("no table 'tableID' found for url {}".format(url))
        print("html content:\n{}\n".format( page.content))
        continue
    res = res.append(table_to_df(table))
    res.to_csv(os.path.join(PATH,"BIC","table.csv"), index=False, sep=',', encoding='iso-8859-1')
    url = next_page(soup)
    counter += 1

相关问题 更多 >