python - 如何将 Beautiful soup 输出数据保存到文本文件中?

标签 python python-2.7 file-io beautifulsoup

如何将我的 Beautiful soup 输出数据保存到文本文件中?
这是代码;

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()

最佳答案

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')

关于python - 如何将 Beautiful soup 输出数据保存到文本文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34833951/

相关文章:

python - 匹配两个二维数组的行并使用 numpy 获取行索引映射

python - 使用修改后的副本隐藏全局变量

python - 将字典元组转换为嵌套字典

matlab - 在 MATLAB 中跳过阅读标题

python - 登录多处理和多线程python程序?

python - 用 Pandas 选择前 n 列和最后 n 列

python - "for chunk in response.iter_content(1024)"引发 StreamConsumedError() 异常

Python read() 似乎返回的数据少于它读取的数据

C++按行读取逗号分隔文件[其中一个部分为mm/dd/yyyy],安全地放入结构中

python - aggregate(Max ('id' )) 返回异常 'str' 对象没有属性 'email'