writer.writeheader('title', 'flood', 'address', 'followInfo', 'tag') # 写入标题行 TypeError: writeheader() takes 1 positional argument but 6 were given
时间: 2024-01-05 07:02:22 浏览: 162
Python用csv写入文件_消除空余行的方法
`writer.writeheader()` 方法不接受参数,它只是用来写入标题行。要解决这个问题,你可以使用 `writer.writerow()` 方法来手动写入标题行。以下是修改后的代码:
```python
import requests
from lxml import etree
import time
import csv
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
with open("data.csv", mode="a", encoding="utf-8", newline='') as f:
writer = csv.writer(f)
# 写入标题行
writer.writerow(['title', 'flood', 'address', 'followInfo', 'tag'])
for start in range(0, 2):
url = f"https://cs.lianjia.com/ershoufang/pg{start}/"
resp = requests.get(url=url, headers=headers)
html = etree.HTML(resp.text)
divs = html.xpath('/html/body/div[4]/div/ul/li/div[1]')
for div in divs:
title = div.xpath('./div[1]/a/text()')[0]
flood = '-'.join(div.xpath('./div[2]//a/text()'))
address = div.xpath('./div[3]/div/text()')[0]
followInfo = div.xpath('./div[4]/text()')[0]
tag = ','.join(div.xpath('./div[5]//text()'))
row = [title, flood, address, followInfo, tag]
writer.writerow(row)
```
以上代码会在每次运行时,在 `data.csv` 文件中追加新的数据。标题行会在每次运行时都被写入一次。你可以根据需要调整循环的范围和文件名。
阅读全文