我用bs4編寫了一個Python 3程序,以便成功獲取維基百科的子類別。現在,我可以看到打印結果,但我無法將結果寫入文件。如何寫一個文件作爲我的打印?
from bs4 import BeautifulSoup
import requests
import csv
url = 'https://en.wikipedia.org/wiki/Category:proprietary software'
content = requests.get(url).content
soup = BeautifulSoup(content,'lxml')
noOFsubcategories = soup.find('p')
print('------------------------------------------------------------------')
print(noOFsubcategories.text+'------------------------------------------------------------------')
tag = soup.find('div', {'class' : 'mw-category'})
links = tag.findAll('a')
#print(links)
counter = 1
for link in links:
print (str(counter) + " " + link.text)
counter = counter + 1
with open('subcategories.csv', 'a') as f:
f.write(links)
你能更準確地解答這個問題嗎?怎麼了?你期望什麼? – jonrsharpe
當我在python3中執行上面的代碼時,輸出文件是空的。所以,我發佈了上述問題。 –
我通過以下答案解決了問題,並以學習者身份得到通知。對不起我的英語不好。除了我的語言,我絕對不會打字。 –