簡體   English   中英

Python 問題寫入txt文件

[英]Python Issue writing txt file

我正在嘗試將我用 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)

output:

[H] Magma
[H] Pink Light Show
[H] Cristiano
[H] Anodized Pearl

但是當我再次寫它時,output:

[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)進行截斷,但是 output 像這樣:

[H] Anodized Pearl

我應該怎么做才能在循環期間中斷 output 好像它是第一個 output

在進入選擇循環之前,您應該打開文件進行寫入。 像這樣:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM