我需要通過抓取(在法律基礎上)收集一些資料,所以現在在我自己的登錄頁面上測驗腳本。目標是每 3 小時提取一次標簽中的特定文本(在我的示例中只有一個句子)。我每 1 秒測驗一次代碼(所以希望看到 5 行“СОСТАВЛЯЕМ СМЕТЫ”5 秒)。但是代碼的執行只寫了一次短語,然后回傳一個錯誤。
import schedule
import time
from urllib.request import urlopen
from bs4 import BeautifulSoup
mf = open("C:\\Users\\Admin\\Desktop\\huyandex.txt",'a')
def job():
html = urlopen("https://smeta-spb.com/")
#print(html.read())
bsObj = BeautifulSoup(html)
nameList = bsObj.findAll("h1")
#print(len(nameList))
for name in nameList:
mf.write(name.get_text())
mf.write('\n')
mf.close()
schedule.every(5).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)
但錯誤開始:
I/O operation on closed file.
如何轉換代碼以便我可以將內容寫入檔案?
uj5u.com熱心網友回復:
您可以簡單地在回圈中打開一個檔案,從回圈開始處洗掉 open 陳述句并將其移動到里面,這樣您的代碼就變成了:
import schedule
import time
from urllib.request import urlopen
from bs4 import BeautifulSoup
def job():
mf=open("huyandex.txt",'a') # moved it inside the function
html = urlopen("https://smeta-spb.com/")
#print(html.read())
bsObj = BeautifulSoup(html)
nameList = bsObj.findAll("h1")
#print(len(nameList))
for name in nameList:
mf.write(name.get_text())
mf.write('\n')
mf.close()
schedule.every(5).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369460.html
