【问题标题】:Trouble Writing BeautifulSoup Output to File将 BeautifulSoup 输出写入文件时遇到问题
【发布时间】:2014-11-18 20:05:28
【问题描述】:

你好 stackoverflow 社区!

我仍在学习 Python 编码的细节,所以请原谅我即将发布的代码。

我目前正在尝试编写一个脚本,该脚本将使用 BS4 从http://kat.ph 抓取最新的媒体种子列表并将其保存到文件中。但是,我无法将 BS4 的输出打印到此文件。当您打开文本文件时,它是空白的,但是当您在终端中运行脚本时,它工作得很好。最终,我想让 python 在电子邮件中发送 bs4 输出(这是我最初遇到此问题并决定查看是否可以写入 .txt 文件的地方)。

目前我没有在家用电脑上制作的脚本,但我重新创建了另一个我做了几乎相同的事情的脚本。

非常感谢任何帮助/建议!

from bs4 import BeautifulSoup
import requests
import time

#The goal of this script was to scrape the names of the latest media torrents and  write them to a text file.
#When I run the script on my computer, I can see the prompt give me the list of torrents just fine.
#When I try to write to a file or send an email, it doesn't print anything.

req = requests.get('http://kat.ph')

site = req.text

soup = BeautifulSoup(site) #Tried making this 'soup = str(BeautifulSoup(site)) to no avail.

def writingFunction():
    #I imported time module because I had my script display the time and date here.
    counter = 1
    for i in soup.find_all('div', {'class': 'markeredBlock torType filmType'}):

        print str(counter) + '.' + ' ' + i.text
        counter = counter + 1

textFile = open('C:/python27/file.txt', 'a')
textFile.write(writingFunction()) #I've tried making this a str and I've also tried  assigning the function to a variable
textFile.close()

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    只写函数,目前你只是打印输出:

    def writing_function():
        with open('C:/python27/file.txt', 'a') as f:
            for ind, i in enumerate(soup.find_all('div', {'class': 'markedBlock torType filmType'}),1):
                f.write("{}. {}".format(ind, i.text.replace("\n","")))
    

    print str(counter) + '.' + ' ' + i.content.replace('\n', '') 正在打印每一行,您没有返回任何内容,所以textFile.write(writingFunction()) 是徒劳的,只需在函数中编写即可。

    如果您不想硬编码文件名,只需将其作为参数传递:

    def writing_function(my_file):
        with open(my_file, 'a') as f:
    

    使用带有1 起始索引的enumerate 将执行您的计数器变量正在执行的操作。

    bs4中没有.content,它是contents,这是一个列表,如果你想要文本使用i.text

    【讨论】:

    • 不打印的唯一方法是你的 find_all 什么也没找到
    • 如果我告诉你这行不通,你不会相信我的。我按照你说的使用了 enumerate 函数,但它仍然打印空白。
    • 您的 find_all 肯定什么也没找到,所以文件为空是有道理的,您是否真的尝试打印 findall 的内容以查看那里有什么
    • 你说对了一件事:我没有从 find_all 得到任何回报。我拼错了 div 标签中的一个元素。我更正了,它打印到文件中。唯一的问题是,它返回一堆“无”值。
    • 然后在写之前检查,if i.content is not None:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    相关资源
    最近更新 更多