首页 > 解决方案 > Python 3 Beautiful Soup 4 .findall 不工作

问题描述

我是python和beautifulsoup的新手,如果这是一个愚蠢的问题,我很抱歉。我试图创建一个网络爬虫,它采用输入国家的名称并从以下网站 ( https://tradingeconomics.com/country-list/money-supply-m2 ) 找到其货币供应量。每当我尝试查找所有 a 标签时,它都会一直给我这个错误:

"AttributeError: ResultSet object has no attribute 'find_all'. 
You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()? "

每当我删除 .find_all(a) 时,它都会起作用。

这是我的代码:

from bs4 import BeautifulSoup
import requests



url4='https://tradingeconomics.com/country-list/money-supply-m2'
def run_scraper():
  print('running')
  country=input('Please input the name of the country: ')
  
  content4=requests.get(url4).text
  soup4=BeautifulSoup(content4,'html.parser')
  t=country.title()


  table=soup4.find('table',{'class':'table table-hover'})
  for tr in table.find_all('tr'):
    co=tr.find_all('td').find_all('a')
    print(co)
      

run_scraper()

有人可以告诉我我做错了什么吗?

谢谢你。

标签: pythonbeautifulsoup

解决方案


find_all返回(本质上)一个列表。列表没有find_all方法。

您需要遍历所有td元素,就像您已经遍历所有tr元素一样:

for tr in table.find_all('tr'):
    for td in tr.find_all('td'):
        co = td.find_all('a')
        print(co)

推荐阅读