我正在尝试使用Beautiful Soup刮擦一张简单的桌子。这是我的代码:
import requests
from bs4 import BeautifulSoup
url = 'https://gist.githubusercontent.com/anonymous/c8eedd8bf41098a8940b/raw/c7e01a76d753f6e8700b54821e26ee5dde3199ab/gistfile1.txt'
r = requests.get(url)
soup = BeautifulSoup(r.text)
table = soup.find_all(class_='dataframe')
first_name = []
last_name = []
age = []
preTestScore = []
postTestScore = []
for row in table.find_all('tr'):
col = table.find_all('td')
column_1 = col[0].string.strip()
first_name.append(column_1)
column_2 = col[1].string.strip()
last_name.append(column_2)
column_3 = col[2].string.strip()
age.append(column_3)
column_4 = col[3].string.strip()
preTestScore.append(column_4)
column_5 = col[4].string.strip()
postTestScore.append(column_5)
columns = {'first_name': first_name, 'last_name': last_name, 'age': age, 'preTestScore': preTestScore, 'postTestScore': postTestScore}
df = pd.DataFrame(columns)
df
但是,每当我运行它时,都会出现此错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-116-a900c2872793> in <module>()
14 postTestScore = []
15
---> 16 for row in table.find_all('tr'):
17 col = table.find_all('td')
18
AttributeError: 'ResultSet' object has no attribute 'find_all'
我已经阅读了大约12个有关此错误的StackOverflow问题,但我无法弄清楚自己在做什么错。
参考方案
table
变量包含一个数组。您需要在其成员上调用find_all
(即使您知道它是一个只有一个成员的数组),而不是整个过程。
>>> type(table)
<class 'bs4.element.ResultSet'>
>>> type(table[0])
<class 'bs4.element.Tag'>
>>> len(table[0].find_all('tr'))
6
>>>
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
python JSON对象必须是str,bytes或bytearray,而不是'dict - python在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…