【问题标题】:After scraping I can not write the text to a text file抓取后我无法将文本写入文本文件
【发布时间】:2021-12-25 23:34:29
【问题描述】:

我正在尝试从网站上获取价格并且它正在工作,但是...我无法将结果写入 text.file。 这是我的python代码。

import requests
from bs4 import BeautifulSoup as bs

url = "https://www.futbin.com/stc/cheapest"

r = requests.get(url)
soup = bs(r.content, "html.parser")
price = soup.find("div", {"class":"d-flex row col-md-9 px-0"})

name =("example")
f =open(name + '.txt', "a")

f.write(price.text)   

这不起作用,但如果我打印它而不是尝试将其写入文本文件,它就会起作用。我搜索了很长时间,但不明白。我认为它必须是一个字符串才能写入文本文件,但不知道如何将输出更改为字符串。

【问题讨论】:

  • 您的代码适用于我的测试。也许你需要在 f.write() 之后调用 f.close()

标签: python beautifulsoup text-files screen-scraping


【解决方案1】:

由于 unicode 字符,您遇到了错误。 尝试在打开文件时添加encoding='utf-8' 属性。

您的代码也给出了一些混乱的输出。试试这个:

import requests
from bs4 import BeautifulSoup as bs

url = "https://www.futbin.com/stc/cheapest"

r = requests.get(url)
soup = bs(r.content, "html.parser")
rows = soup.find("div", {"class":"d-flex row col-md-9 px-0"})
prices = rows.findAll("span",{"class":"price-holder-row"})
names = rows.findAll("div",{"class":"name-holder"})
price_list = []
name_list = []
for price in prices:
    price_list.append(price.text.strip("\n "))
for name in names:
    name_list.append(name.text.split()[0])
name =("example")
with open(f"{name}.txt",mode='w', encoding='utf-8') as f:
    for name, price in zip(name_list,price_list):
        f.write(f"{name}:{price}\n")

【讨论】:

  • 太棒了!谢谢你,这对我很有帮助。
  • 不客气。你可以通过投赞成票来感谢我。 Stackoverflow 上不允许写感谢信。
  • 我不能投票,因为我是新人......
猜你喜欢
  • 2015-06-19
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
相关资源
最近更新 更多