我試圖從所有我一直在看教程下載原始代碼寫的,所以我做了這個:使用循環中的文件
import requests
from urllib import request
from bs4 import BeautifulSoup
page_url='https://github.com/buckyroberts/Source-Code-from-
Tutorials/tree/master/Python'
def page(main_url):
code=requests.get(main_url)
text=code.text
soup=BeautifulSoup(text, "html.parser")
for link in soup.findAll('a', {'class': 'js-navigation-open'}):
code_url='https://github.com'+link.get('href')
codelist(code_url)
def codelist(sec_url):
code = requests.get(sec_url)
text = code.text
soup = BeautifulSoup(text, "html.parser")
for link in soup.findAll('a', {'id': 'raw-url'}):
raw_url='https://github.com'+link.get('href')
rawcode(raw_url)
def rawcode(third_url):
response = request.urlopen(third_url)
txt = response.read()
lines = txt.split("\\n")
dest_url = r'go.py'
fx = open(dest_url, "w")
for line in lines:
fx.write(line + "\n")
fx.close()
page(page_url)
當我運行此代碼我希望創造40 PY由40個不同代碼組成的文件 - https://github.com/buckyroberts/Source-Code-from-Tutorials/tree/master/Python 但它不起作用。它兩次隨機選擇只下載40個文件中的一個。像這樣 -
前兩個函數一起工作良好,直到第三個函數被調用。但第三個單獨運作良好。
我開始學習Python 4天后,任何幫助將不勝感激。感謝你們!
找你e寫在您的文件上,刪除前一個文件及其內容。嘗試'fx = open(dest_url,「a」)',它將(a)dd代碼而不是重新(w)rtten – Nuageux
最好將保存在不同的文件中(你可以用一個簡單的計數器將增加,從而改變文件名稱)。所以你可以在 – Nuageux
@Nuageux之後運行它們謝謝,先生。無法想象一個字母解決了它。 但是,所有的代碼仍然被下載到一個文件中。你會推薦什麼來循環它以創建40個不同的文件? 再次感謝。 – SorainOne