栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Python在网页上下载所有链接(相关文档)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Python在网页上下载所有链接(相关文档)

这是如何从http://pypi.python.org/pypi/xlwt下载一些选定文件的示例

您将需要先安装机械化:http :
//wwwsearch.sourceforge.net/mechanize/download.html

    import mechanize    from time import sleep    #Make a Browser (think of this as chrome or firefox etc)    br = mechanize.Browser()    #visit http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/    #for more ways to set up your br browser object e.g. so it look like mozilla    #and if you need to fill out forms with passwords.    # Open your site    br.open('http://pypi.python.org/pypi/xlwt')    f=open("source.html","w")    f.write(br.response().read()) #can be helpful for debugging maybe    filetypes=[".zip",".exe",".tar.gz"] #you will need to do some kind of pattern matching on your files    myfiles=[]    for l in br.links(): #you can also iterate through br.forms() to print forms on the page!        for t in filetypes: if t in str(l): #check if this link has the file extension we want (you may choose to use reg expressions or something)     myfiles.append(l)    def downloadlink(l):        f=open(l.text,"w") #perhaps you should open in a better way & ensure that file doesn't already exist.        br.click_link(l)        f.write(br.response().read())        print l.text," has been downloaded"        #br.back()    for l in myfiles:        sleep(1) #throttle so you dont hammer the site        downloadlink(l)

注意:在某些情况下,您可能希望替换

br.click_link(l)
br.follow_link(l)
。区别在于click_link返回一个Request对象,而follow_link将直接打开该链接。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/641317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号