我已经在网站上进行了网络练习,我正在尝试将数据放入可以导出到csv的pandas数据框中,当我到达TypeError: __init__() got multiple values for argument 'fieldnames'
时出现的点。我想使用csv模块编写文件。有人可以解释错误是如何发生的以及如何解决它?我的代码如下:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import csv
my_url = 'https://www.allagents.co.uk/find-agent/london/'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, 'html.parser')
containers = page_soup.findAll('div', {'class':'itemlabel3'})
filename = "webscrape.csv"
records = []
for container in containers:
comp_name = container.find('div', {'class':'labelleft2 col-md-10'}).div.h4.a.text
address=container.find('div', {'class':'labelleft2 col-md-10'}).div.p.text.replace('\n','')
tel = container.find('div', {'class':'labelleft2 col-md-10'}).div.find('p', {'style':'clear: both; margin-bottom: 15px;'}).strong.text
records.append({'company': comp_name, 'address': address, 'telephone': tel})
writer = csv.DictWriter(filename, "w", fieldnames=['company', 'address', 'telephone'])
writer.writeheader()
for r in records:
writer.writerow(r)
出现错误:
writer = csv.DictWriter(filename, "w", fieldnames=['company', 'address', 'telephone'])
在此先感谢,感谢任何帮助。
答案 0 :(得分:2)
在csv.DictWriter
中,前两个参数是文件对象(不是文件名),然后是fieldnames
(您指定为"w"
)。试试这个:
with open(filename, 'w') as f:
writer = csv.DictWriter(f, ['company', 'address', 'telephone'])
# write stuff in this block
答案 1 :(得分:1)
我怀疑您对DictWriter
的来电有太多参数:
writer = csv.DictWriter(filename, "w", fieldnames ...
^
what is this?
我认为它应该是:
f = open(filename, 'w')
writer = csv.DictWriter(f, fieldnames ...
在您的通话中,fieldnames
参数已分配"w"
,但您也提供自己的版本作为列表。