【问题标题】:Pytho, BeautifulSoup - web scraping 'find_all' is returning NoneTypePython,BeautifulSoup - 网络抓取“findall”正在返回 NoneType
【发布时间】:2020-11-07 04:24:28
【问题描述】:

我正在尝试抓取网站,下面的图片就是我得到的。 url = 'https://www.worldometers.info/world-population/population-by-country/'

我已经在 stackoverflow 上尝试过所有类似的解决方案,但它对我不起作用

table_data=soup.find('table', {"id" : "example2"}, class_='table table-striped table-bordered dataTable no-footer')

headers = []
for i in table_data.find_all('th'):
    title = i.text
    headers.append(title)

Error message
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-129-e8b5de995a9d> in <module>
      1 table_data=soup.find('table', {"id" : "example2"}, class_='table table-striped table-bordered dataTable no-footer')
      2 headers = []
----> 3 for i in total_data.find_all('th'):
      4     title = i.text
      5     headers.append(title)

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

这是我在抓取表格时尝试使用的代码,但它也不起作用。进一步的帮助

for j in table_data.find_all('tr')[1:]:
        row_data = j.find_all('td')
        row = [tr.text for tr in row_data]
        length = len(df)
        df.loc[length] = row


ValueError: cannot set a frame with no defined columns

【问题讨论】:

  • 什么是total_data?你的意思是table_data

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

“findAll”是一个漂亮的汤函数,这意味着你必须使用:

soup.findAll('th')

【讨论】:

    【解决方案2】:

    我查看了该页面并使用过:

    table_data = soup.find('table', id="example2")
    columns = [x.text for x in table_data.find("thead").find_all("th")][1:]
    rows = [[x.text for x in y.find_all("td")][1:] for y in table_data.find("tbody").find_all("tr")]
    dt = pd.DataFrame(rows, columns=columns)
    

    测试它;-)

    【讨论】:

    • @dhrey112 哦!让我删除我的答案。找到桌子。
    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多