简体   繁体   English

Python 列表到 csv 文件

[英]Python list into csv file

I created a scraper to get info from a website using a for loop and created a list with each loop.我创建了一个刮板来使用 for 循环从网站获取信息,并为每个循环创建了一个列表。 The result is what I expected but I'm having a hard time to put this info altogether into a csv file.结果是我所期望的,但我很难将这些信息完全放入一个 csv 文件中。 My intention is to create 4 rows where the corresponding url, location, etc, will match but I maybe the way that I set my loops is making it harder?我的目的是创建 4 行,其中相应的 url、位置等将匹配,​​但我设置循环的方式可能使它变得更难?

I thought the the follow syntax would do the trick but nah.我认为以下语法可以解决问题,但不。 It only prints all the urls in the same row.它只打印同一行中的所有 url。 I got to print all the info but they were still in the same row.我必须打印所有信息,但它们仍然在同一行。

with open('trademe.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['URL', 'Price', 'Location', 'Flatmates'])
    writer.writerow([link, price, loc, mates])

By the way, this is the code so far;顺便说一下,这是到目前为止的代码;

trademe = urlopen(url)
trademe_html = soup(trademe.read(), "html.parser")
trademe.close()

link=[]
for i in trademe_html.find_all('div', attrs={'class' : 'dotted'}):
    link.append('URL: www.trademe.co.nz'+i.a['href'])
    print('URL: www.trademe.co.nz'+i.a['href'])

price=[]
for i in trademe_html.find_all('div', attrs={'class' : 'flatmates-list-view-card-price'}):
    price.append('Price and availability: ' + i.text.strip())
    print('Price and availability: ' + i.text)

loc=[]
for i in trademe_html.find_all('div', attrs={'class' : 'flatmates-card-subtitle'}):
    loc.append('Location: ' + i.text)
    print('Location: ' + i.text)
    
mates=[]
for i in trademe_html.find_all('div', attrs={'class' : 'flatmates-card-existing-flatmates'}):
    mates.append(i.text.strip())
    print(i.text)
  • Insert your data into a pandas DataFrame将您的数据转换为pandas DataFrame
  • Use the to_csv function in pandas使用to_csv在功能pandas

Pandas makes it really easy to export a DataFrame to csv with headers Pandas 使将 DataFrame 导出到带有标题的 csv 变得非常容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM