Jon*_*hon 0 python io file beautifulsoup
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("youtube.htm"))
for link in soup.find_all('img'):
print link.get('src')
file = open("parseddata.txt", "wb")
file.write(link.get('src')+"\n")
file.flush()
Run Code Online (Sandbox Code Playgroud)
您好,我想尝试使用BeautifulSoup并解析一些youtube网站.它得到了 这条线路有25条线路.但是,如果我查看文件,那么只写了最后一个(其中一小部分).我尝试了不同的打开模式,或者file.close()函数.但没有任何效果.有人知道了吗?
您循环遍历此行中的每个img标记并打印每个标记:
for link in soup.find_all('img'):
print link.get('src')
Run Code Online (Sandbox Code Playgroud)
但是,您不是在该循环中写入文件,而是link.get('src')+'\n'在最后编写.
这只会写出当前分配的链接,这只是您在上面循环中找到的最后一个 img标记.这就是为什么只有一个'src'值将被写入输出文件.
您需要将每行写入循环中的文件,该文件将遍历您感兴趣的每个img标记.您需要进行一些重新排序才能执行此操作:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("youtube.htm"))
file = open("parseddata.txt", "wb")
for link in soup.find_all('img'):
print link.get('src')
file.write(link.get('src')+"\n")
file.flush()
file.close()
Run Code Online (Sandbox Code Playgroud)
你还应该记得关闭我在上面代码片段最后一行添加的文件.
编辑:根据下面的Hooked评论,如果您使用with关键字,此片段就是这样的内容.使用with将在缩进块结束后自动为您关闭文件,这样您甚至不必考虑它:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("youtube.htm"))
with open("parseddata.txt", "wb") as file:
for link in soup.find_all('img'):
print link.get('src')
file.write(link.get('src')+"\n")
Run Code Online (Sandbox Code Playgroud)