CSV何时不生成

时间:2019-04-24 05:28:25

标签: python beautifulsoup export-to-csv

它不会生成。

完成后,文件为空白。

    import csv
import requests 
from bs4 import BeautifulSoup as bs
for i in range(3):
        r = requests.get('https://www.nairaland.com/search/afonja/0/0/0/{}'.format(i))
        soup = bs(r.content, 'lxml')
        occurrences = len(soup.select('.highlight')) #if soup.select_one('.highlight') else 
    z=[occurrences]
    with open('z.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow([z]) 

1 个答案:

答案 0 :(得分:0)

您需要将所有出现的值收集到一个列表中,而不是每次通过循环都覆盖该列表。循环后,将列表写入CSV文件。

由于z已经是一个列表,因此在将[z]写入文件时无需写入。

import csv
import requests 
from bs4 import BeautifulSoup as bs
z = []
for i in range(3):
    r = requests.get('https://www.nairaland.com/search/afonja/0/0/0/{}'.format(i))
    soup = bs(r.content, 'lxml')
    occurrences = len(soup.select('.highlight'))
    z.append(occurrences)
with open('z.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(z)