我正在嘗試將我用python中的beautifulsoup決議的元素寫入一個txt檔案,我需要在寫入之前截斷它,因為它會被更新。
這就是我撰寫決議的元素的方式
url = "https://rocket-league.com/trade/465ec00f-2f5c-48e2-831e-2e294683ad56"
response = requests.get(f"{url}")
soup = BeautifulSoup(response.text, "html.parser")
for e in soup.select('.rlg-trade__itemshas .--hover'):
items = (' '.join(list(e.stripped_strings)[:-2]))
lstitem = (f"[H] " f"{items}" f"\n")
with open("hs.txt", "a") as h:
h.write(lstitem)
輸出:
[H] Magma
[H] Pink Light Show
[H] Cristiano
[H] Anodized Pearl
但是當我再次寫它時,輸出:
[H] Magma
[H] Pink Light Show
[H] Cristiano
[H] Anodized Pearl
[H] Magma
[H] Pink Light Show
[H] Cristiano
[H] Anodized Pearl
我h.truncate(0)在寫作之前使用截斷,但輸出如下:
[H] Anodized Pearl
我應該怎么做才能在回圈期間中斷輸出,就好像它是第一個輸出一樣
uj5u.com熱心網友回復:
在進入選擇回圈之前,您應該打開檔案進行寫入。像這樣:
import requests
from bs4 import BeautifulSoup
OUTPUT = 'hs.txt'
url = "https://rocket-league.com/trade/465ec00f-2f5c-48e2-831e-2e294683ad56"
(response := requests.get(url)).raise_for_status()
soup = BeautifulSoup(response.text, 'lxml')
with open(OUTPUT, 'w') as h:
for e in soup.select('.rlg-trade__itemshas .--hover'):
item = ' '.join(list(e.stripped_strings)[:-2])
print(f'[H] {item}', file=h)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505046.html
上一篇:當csv檔案中存在空格時,Psycopg2copy_from()正在使用雙引號插入資料
下一篇:執行緒安全的檔案更新
