所以我有这段代码:
#! python3
import requests
import bs4
import time
import sys
messages = []
for i in range(3):
# initiating request
res = requests.get('https://supermariomakerbookmark.nintendo.net/')
try:
res.raise_for_status()
except Exception as e:
# handling error
print('Error while requesting from bookmark:')
print(e)
time.sleep(3)
sys.exit()
# If gotten to this point, request has been succesfully made
# creating soup element
soup = bs4.BeautifulSoup(res.text, features='html.parser')
# selecting elements
elems = soup.select('div[class="course-title"]')
if elems[0].getText() not in messages:
print(elems[0].getText())
messages.append(elems[0].getText())
time.sleep(0.3)
with open('db.txt', 'w+') as f:
data = '\n'.join(messages).encode('ascii', 'ignore')
f.write(str(data))
您可能已经发现,我正在尝试在名为db.txt
的文件中写出3个随机的Mario制造商级别(很显然,我不会仅将其用于3个级别,大概是500/700,但这只是一个例子)。
问题是,当我检查txt文件时,它将是这样的:
b"foo\nbar\nbaz"
但是我想要这样:
b"""
foo
bar
baz
"""
有人可以帮我吗?
答案 0 :(得分:0)
替换
data = '\n'.join(messages).encode('ascii', 'ignore')
使用
data = '\n'.join(messages)