这是我的第一个Python项目,所以它非常基础和基本。 我经常要为朋友清除病毒,我使用的免费程序也经常更新。我没有手动下载每个程序,而是尝试创建一个简单的方法来自动化这个过程。由于我也在努力学习python,所以我认为这是一个练习的好机会。在
问题:
我必须找到带有一些链接的.exe文件。我可以找到正确的网址,但我得到一个错误时,它试图下载。在
有没有一种方法可以将所有链接添加到一个列表中,然后创建一个函数来遍历列表并在每个url上运行该函数?我已经用了很多谷歌,但我似乎不能让它工作。也许我的想法不对吧?在
import urllib, urllib2, re, os
from BeautifulSoup import BeautifulSoup
# Website List
sas = 'http://cdn.superantispyware.com/SUPERAntiSpyware.exe'
tds = 'http://support.kaspersky.com/downloads/utils/tdsskiller.exe'
mbam = 'http://www.bleepingcomputer.com/download/malwarebytes-anti-malware/dl/7/?1'
tr = 'http://www.simplysup.com/tremover/download.html'
urllist = [sas, tr, tds, tr]
urrllist2 = []
# Find exe files to download
match = re.compile('\.exe')
data = urllib2.urlopen(urllist)
page = BeautifulSoup(data)
# Check links
#def findexe():
for link in page.findAll('a'):
try:
href = link['href']
if re.search(match, href):
urllist2.append(href)
except KeyError:
pass
os.chdir(r"C:\_VirusFixes")
urllib.urlretrieve(urllist2, os.path.basename(urllist2))
如您所见,我将函数注释掉了,因为我无法使其正常工作。在
我应该放弃这个列表而单独下载吗?我在努力提高效率。在
如有任何建议或您能为我指出正确的方向,我们将不胜感激。在
除了mikez302's answer之外,还有一种更具可读性的编写代码的方法:
上面的代码对我不起作用,在我的例子中,这是因为页面通过一个脚本组装它们的链接,而不是包含在代码中。当我遇到这个问题时,我使用了以下代码,这只是一个刮刀:
这并不如前面的答案中的代码有效,但它几乎适用于大多数网站。在
urllib2.urlopen
是访问单个URL的函数。如果你想访问多个,你应该在列表中循环。你应该这样做:相关问题 更多 >
编程相关推荐