2017-06-29 35 views
0

我試圖從所有我一直在看教程下載原始代碼寫的,所以我做了這個:使用循環中的文件

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天后,任何幫助將不勝感激。感謝你們!

+0

找你e寫在您的文件上,刪除前一個文件及其內容。嘗試'fx = open(dest_url,「a」)',它將(a)dd代碼而不是重新(w)rtten – Nuageux

+0

最好將保存在不同的文件中(你可以用一個簡單的計數器將增加,從而改變文件名稱)。所以你可以在 – Nuageux

+0

@Nuageux之後運行它們謝謝,先生。無法想象一個字母解決了它。 但是,所有的代碼仍然被下載到一個文件中。你會推薦什麼來循環它以創建40個不同的文件? 再次感謝。 – SorainOne

回答

0

[繼評論]爲了輕鬆更改文件名,你可以添加一個全局變量(這裏cp)如如下:

def rawcode(third_url): 
    global cp 
    dest_url = r'go_%s.py' % cp 
    cp += 1 
    print(dest_url) 

cp = 0 
page(page_url) 

的文件名稱將是「go_X.py"從0 X將文件

編輯 與您的代碼數量:

def rawcode(third_url): 
    response = request.urlopen(third_url) 
    txt = response.read() 
    lines = txt.split("\\n") 
    global cp # We say that we will use cp the global variable and not local one 
    dest_url = r'go_%s.py' % cp 
    cp += 1 # We increment for further calls 
    fx = open(dest_url, "w") # We can keep 'w' since we will generate new files at each call 
    for line in lines: 
     fx.write(line + "\n") 
    fx.close() 

cp = 0 # Initialisation 
page(page_url) 
+0

謝謝,先生。你讓我今天一整天都感覺很好。 :) – SorainOne

+0

不客氣。隨意將您的問題標記爲已回答 – Nuageux

+0

先生,我不知道該怎麼做。這裏很新。 – SorainOne