![](/img/trans.png)
[英]How can I create new directory and save file using urllib2 in Python?
[英]How to get latest file using “urllib2” by reading html directory in python
我想從http文件夾中讀取最新文件
'releases'文件夾應該像0001.tgz,0002.tgz,0003.tgz如何制作0003將被選中?
import urllib2
url = "http://example.com/releases"
html = urllib2.urlopen(url).read()
...
謝謝。 給我一些例子。
您可以使用BeautifulSoup
或lxml
來解析目錄索引,並根據您的命名約定查找最新文件,該文件可能是索引中的最后一個文件。
像這樣的東西:
from bs4 import BeautifulSoup
import urllib2
url = "http://example.com/releases"
html = urllib2.urlopen(url).read()
soup = BeautifulSoup(html)
last_link = soup.find_all('a', href=True)[-1]
latest_content = urllib2.urlopen(last_link['href']).read()
# do stuff
如果這不起作用,請使用find_all
獲取所有鏈接,並根據文件名進行更仔細的解析。
如果.tgz文件是順序的,那么從最大值開始倒計時,當你到達第一個(最新的)文件時停止循環。
import urllib2
for counter in xrange(9999,0,-1):
fyle = str(counter).zfill(4) # pad zeros
url = "http://example.com/releases/"+fyle+".tgz"
ret = urllib2.urlopen(url)
if ret.code == 200:
print "Exists:",fyle
break
html = urllib2.urlopen(url).read()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.