[英]BeautifulSoup Python saving Output links to txt file
我正在嘗試使用BeautifulSoup來收集網頁上的鏈接。 到目前為止,我已經能夠做到這一點,並使用當前代碼注釋掉的打印命令在命令提示符下將其打印出來。 我遇到的問題是將鏈接保存到Output.txt文件時,它們全部相互覆蓋,並且僅保存了最后一個鏈接。 任何幫助深表感謝!
如果您有任何關於在一個程序中進行全部轉換的指示,請參閱我的最終目標。 我的最終目標是搜索txt文件中的鏈接,以確定其中是否包含特定文本。 如果他們這樣做,我想返回“ Broken Link”或“ Not Broken”。
soup = BeautifulSoup(html_doc) #html doc is source code for website i am using
for link in soup.find_all(rel="bookmark"):
Gamma =(link.get('href'))
f =open('Output.txt','w')
f.write(Gamma)
f.close()
#print(Gamma)
您需要在循環之前打開要寫入的文件,然后在其中調用write()
:
soup = BeautifulSoup(html_doc)
with open('Output.txt','w') as f:
for link in soup.find_all(rel="bookmark"):
f.write(link.get('href'))
另外,請注意, with
上下文管理器with
使用可以幫助您不必擔心手動關閉文件。
只需將“ w”替換為“ a”,使其成為“附加”模式。
soup = BeautifulSoup(html_doc) #html doc is source code for website i am using
for link in soup.find_all(rel="bookmark"):
Gamma =(link.get('href'))
f =open('Output.txt','a')
f.write("{gamma}\n".format(gamma=Gamma))
f.close()
#print(Gamma)`enter code here`
正如其他人所述,您需要附加文件。 進行單個打開和關閉操作也更加高效。
f = open ('Output.txt', 'a')
for link in soup.find_all(rel="bookmark")
Gamma =(link.get('href')
f.write(Gamma + '\n')
f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.