如何使用python在一个文件中写入多行

2024-05-18

如果我知道要写多少行,我就知道如何将多行写入一个文件。但是,当我想写多行时,问题就出现了,但是,我不知道它们会是多少

我正在开发一个应用程序,它从网站上抓取并将结果的链接存储在文本文件中。但是,我们不知道它会回复多少行。我的代码现在如下。

r = requests.get('http://www.crunchyroll.com/i-cant-understand-what-my-husband-is-saying')
soup = BeautifulSoup(r.text)
print soup.title
subtitles = soup.findAll('div',{'class':'wrapper container-shadow hover-classes'})
for episode in subtitles:
  x = episode.find_all('a')
  for a in x:
   #print a['href']

   z = a['href']

  l = 'http://www.crunchyroll.com'+ z
  print l

这给了我想要的输出。所以,我尝试通过添加以下内容在文件中写入内容:

file = open("BatchLinks.txt", "w")
file.write(l)
file.close()

但不幸的是,它只写第一个链接。我怎样才能添加其他链接?


确保将链接写入 for 循环内。用一个with命令也可以让您手动关闭文件。 这应该有效:

r = requests.get('http://www.crunchyroll.com/i-cant-understand-what-my-husband-is-saying')
soup = BeautifulSoup(r.text)
print soup.title
subtitles = soup.findAll('div',{'class':'wrapper container-shadow hover-classes'})

with open("BatchLinks.txt","w") as file: 

    for episode in subtitles:
        x = episode.find_all('a')
        for a in x:

            z = a['href']

            link = 'http://www.crunchyroll.com'+ z
            print link
            file.write(link)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用python在一个文件中写入多行 的相关文章

随机推荐