如何将我的美味汤输出数据添加到文本文件中?

时间:2016-01-17 01:01:34

标签: python python-2.7 file-io beautifulsoup

如何将我的美味汤输出数据输入文本文件? 这是代码;

import urllib2

from bs4 import BeautifulSoup

url = urllib2.urlopen("http://link").read()

soup = BeautifulSoup(url)

file = open("parseddata.txt", "wb")

for line in soup.find_all('a', attrs={'class': 'book-title-link'}):

 print (line.get('href'))

 file.write(line.get('href'))

 file.flush()

 file.close()

2 个答案:

答案 0 :(得分:2)

file.close应该被调用一次(在for循环之后):

import urllib2
from bs4 import BeautifulSoup

url = urllib2.urlopen("http://link").read()
soup = BeautifulSoup(url)
file = open("parseddata.txt", "wb")
for line in soup.find_all('a', attrs={'class': 'book-title-link'}):
    href = line.get('href')
    print href
    if href:
        file.write(href + '\n')
file.close()

更新您可以使用href=True来避免if声明。除此之外,使用with statement,您无需手动关闭文件对象:

import urllib2
from bs4 import BeautifulSoup


content = urllib2.urlopen("http://link").read()
soup = BeautifulSoup(content)

with open('parseddata.txt', 'wb') as f:
    for a in soup.find_all('a', attrs={'class': 'book-title-link'}, href=True):
        print a['href']
        f.write(a['href'] + '\n')

答案 1 :(得分:0)

我这样做:

with open('./output/' + filename + '.html', 'w+') as f:
    f.write(temp.prettify("utf-8"))

temp是由beautifulsoup赞美的html。