【问题标题】:Why do I get an "AttributeError: 'str' object has no attribute 'write' " in this python code为什么我在这个 python 代码中得到一个“AttributeError: 'str' object has no attribute 'write'”
【发布时间】:2015-10-24 22:11:37
【问题描述】:

我正在尝试将漂亮的汤对象中的文本保存到文件中,以便以后编辑和使用。我已经导入了所有必要的模块,但由于某种原因,我每次在“pagename.write(str(soup))”处都会遇到相同的错误 我试过用多种方式重写,我只是难住了

#Testing implementation of writing to file
#save the HTML to a beautiful soup object
soup = BeautifulSoup(browser.page_source, 'html.parser')

#TODO: use breadcrumb of page name for loop later on
breadcrumb = soup.select('.breadcrumb span')
pagename = breadcrumb[0].get_text()

#open a file then write to it
bookPage = os.path.join('books/cpp/VST', pagename+'.txt')
open(pagename, 'wb')
pagename.write(str(soup))

#close file
#pagename.close()


#TODO: move on to next file

【问题讨论】:

  • pagename 是字符串,不是文件对象

标签: python python-3.x beautifulsoup


【解决方案1】:

pagename 是一个字符串 - 从 HTML 中提取的文件名。

您的意思是使用bookPage 路径和with context manager。另外,为了避免 TypeError: a bytes-like object is required, not 'str' 错误并获得一个字节串,你需要调用encode():

with open(bookPage, 'wb') as f:
    f.write(soup.encode("utf-8"))

【讨论】:

  • 感谢您的回答!但是现在我收到一个类型错误:TypeError: a bytes-like object is required, not 'str'
  • @DakotaLorance 好吧,你叫它f.write(soup.encode("utf-8")) 怎么样?
猜你喜欢
  • 2021-08-24
  • 2017-10-26
  • 2022-11-14
  • 2020-04-26
  • 2021-05-24
  • 1970-01-01
相关资源
最近更新 更多