如何解决尝试使用 Python 从页面中抓取并将此信息放入 csv 中,仅获取列表最后一个元素的结果
我正在尝试使用 Python 从多个 Ballotpedia 页面中抓取并将此信息放入 csv 中,但我只获得了列表最后一个元素的结果。这是我的代码:
import pandas as pd
list = ['https://ballotpedia.org/Alaska_Supreme_Court','https://ballotpedia.org/Utah_Supreme_Court']
for page in list:
frame = pd.read_html(page,attrs={"class":"wikitable
sortable jquery-tablesorter"})[0]
frame.drop("Appointed By",axis=1,inplace=True)
frame.to_csv("18-TEST.csv",index=False)
我一直在尝试添加和删除代码最后一行的部分内容,但问题仍然存在。必须将列表的第一个元素添加到 csv 中,但它们会被第二个元素替换。我怎样才能让两者同时显示在 csv 上?非常感谢!
解决方法
代码存在三个问题
-
frame.to_csv
在循环之外,所以只在最后一帧执行一次 - 即使它在里面,它也会在每次迭代时覆盖同一个文件
'18-TEST.csv'
-
list
是保留关键字,您不应将其用作变量名
尝试这样的事情
import pandas as pd
page_list = ['https://ballotpedia.org/Alaska_Supreme_Court','https://ballotpedia.org/Utah_Supreme_Court']
for n,page in enumerate(page_list):
frame = pd.read_html(page,attrs={"class":"wikitable
sortable jquery-tablesorter"})[0]
frame.drop("Appointed By",axis=1,inplace=True)
frame.to_csv(f"18-TEST-{n}.csv",index=False)
这会将每个页面保存在不同的 csv '18-TEST-0.csv'、'18-TEST-1.csv'、...
,每次迭代都会重置您的 frame
变量,因此它会被丢弃。您必须将所有条目累积在一个数据框中才能将其全部保存为一个 csv。此外,就像提到的piterbarg,list
是Python 中的保留字。这不会破坏您的代码,但这是不好的做法;)
import pandas as pd
# better variable name "pages"
pages = ['https://ballotpedia.org/Alaska_Supreme_Court','https://ballotpedia.org/Utah_Supreme_Court']
# dataframe outside the loop to accumulate everything in
judges = pd.DataFrame()
for page in pages:
frame = pd.read_html(page,attrs={'class': 'wikitable sortable jquery-tablesorter'})[0]
frame.drop('Appointed By',inplace=True)
# add this particular page's data to the main dataframe
judges = judges.append(frame,ignore_index=True)
# ignore_index ignores the indices from the frame we're adding,# so the indices in the judges frame are continuous
# after the loop,save the complete dataframe to a csv
judges.to_csv('18-TEST.csv',index=False)
这会将所有内容保存在一个 csv 中。试试看!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。