【发布时间】:2018-03-01 16:14:17
【问题描述】:
我在 python 中编写了一个脚本来解析网页中的一些数据并通过 panda 将其写入 csv 文件。到目前为止,我所写的内容可以解析该页面中可用的所有表,但如果写入 csv 文件,它会将该页面中的最后一个表写入该 csv 文件。当然,由于循环,数据正在被覆盖。如何修复这个缺陷,以便我的爬虫能够写入来自不同表的所有数据,而不仅仅是最后一个表?提前致谢。
import csv
import requests
from bs4 import BeautifulSoup
import pandas as pd
res = requests.get('http://www.espn.com/nba/schedule/_/date/20171001').text
soup = BeautifulSoup(res,"lxml")
for table in soup.find_all("table"):
df = pd.read_html(str(table))[0]
df.to_csv("table_item.csv")
print(df)
顺便说一句,我希望仅使用 panda 将数据写入 csv 文件。再次感谢。
【问题讨论】:
标签: python python-3.x pandas csv web-scraping