gpt4 book ai didi

Python 脚本未在新行中写入结果 - 新手

转载 作者:行者123 更新时间:2023-12-01 02:31:57 27 4
gpt4 key购买 nike

我正在抓取 IMDB 页面的数据,但当尝试将其写入 CSV 文件时,我只从结果中获取最后一行。

代码下方:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url='http://www.imdb.com/search/title?genres=sci_fi&title_type=feature&sort=user_rating,desc'
uClient = uReq(my_url)
page_html=uClient.read()
uClient.close()
page_soup=soup(page_html,"html.parser")

images=page_soup.findAll("div",{"class":"lister-item-image float-left"})

containers=page_soup.findAll("div",{"class":"lister-item-content"})

filename="scifi.csv"
f=open(filename,"w")

headers="order, title, year"'\n'

f.write(headers)

for container in containers:
number=container.h3.findAll("span",{"class":"lister-item-index unbold text-primary"})
order=number[0].text

atitle=container.h3.findAll("a")
title=atitle[0].text

date=container.h3.findAll("span",{"class":"lister-item-year text-muted unbold"})
year=date[0].text
print("order:" + order)
print("title:" + title)
print("year:" + year)

f.write(order + "," +title+ "," +year + '\n')
f.close()

我正在使用 Anaconda 和 Spyder。看在我看完 youtube、在 google 上搜索之后的爱,我仍然无法理解为什么它没有一个接一个地写在所有的行中。谢谢!

最佳答案

您的 f.write 位于 for 循环之外,因此它只写入最后一行。这应该有效:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url='http://www.imdb.com/search/title?genres=sci_fi&title_type=feature&sort=user_rating,desc'
uClient = uReq(my_url)
page_html=uClient.read()
uClient.close()
page_soup=soup(page_html,"html.parser")

images=page_soup.findAll("div",{"class":"lister-item-image float-left"})

containers=page_soup.findAll("div",{"class":"lister-item-content"})

filename="scifi.csv"
f=open(filename,"w")

headers="order, title, year"'\n'

f.write(headers)

for container in containers:
number=container.h3.findAll("span",{"class":"lister-item-index unbold text-primary"})
order=number[0].text

atitle=container.h3.findAll("a")
title=atitle[0].text

date=container.h3.findAll("span",{"class":"lister-item-year text-muted unbold"})
year=date[0].text
print("order:" + order)
print("title:" + title)
print("year:" + year)
f.write(order + "," +title+ "," +year + '\n')

f.close()

关于Python 脚本未在新行中写入结果 - 新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46716432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com