【发布时间】:2017-06-29 13:04:54
【问题描述】:
我正在尝试从我一直在看的所有教程中下载原始代码,所以我做了这个:
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 个文件中的一个。像这样-
在调用第三个函数之前,前两个函数可以很好地协同工作。但第三个单独工作正常。
我从 4 天前开始学习 Python,我们将不胜感激。谢谢各位!
【问题讨论】:
-
您已覆盖您的文件,这会删除之前的文件及其内容。试试
fx = open(dest_url, "a"),它将(a)添加代码而不是重新(w)编写它 -
最好是保存在不同的文件中(你可以使用一个简单的计数器来完成,它会增加从而改变文件名)。所以你可以在之后运行它们
-
@Nuageux 谢谢你,先生。无法想象一封信就解决了它。但是,所有代码都下载到一个文件中。你会推荐什么循环它以创建 40 个不同的文件?再次感谢。
-
@Nuageux 将最后一个函数更改为这个,先生 -
x=2 response = request.urlopen(third_url) txt = response.read() txt_str=str(txt) lines = txt_str.split("\\n") dest_url = str(x)+'.py' fx = open(dest_url, "a") for line in lines: fx.write(line + "\n") fx.close() x+=1它创建了一个文件“2.py”并将所有内容保存在其中。我的代码错了吗? -
您在函数的开头定义了
x=2,因此它始终等于 2。我将编辑我的答案,以便您可以复制/粘贴
标签: pycharm python-3.4