Python urllib2返回内容

2024-09-30 22:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何使用错误检查,也得到了网页内容回来。有什么想法吗?你知道吗

我正在尝试获取最旧的文件,然后获取其内容并将其发送到标题中,然后读取网页响应。你知道吗

Python 2.7版。你知道吗

    #!/usr/bin/env python
import os, shutil, time
import urllib, urllib2, cookielib
import serial
fromdir = '/home/pi/scripts/data'
todir = '/home/pi/scripts/dataProcessed'
watch_path = "/home/pi/scripts/data/"
url='http://localhost/data'
fetch_timeout = 10
wait_time = 60
while not sum((len(f) for _, _, f in os.walk(watch_path))):
    print 'No Files present in "' + (watch_path) + '". Checking again in %s' % (wait_time) + ' seconds...'
    time.sleep(wait_time)
else: 
    print 'Files present' 
oldest = ''
oldestAge = 0
for file in os.listdir(watch_path):
    age = os.stat(watch_path + file).st_mtime
    if age > oldestAge:
        oldestAge = age
        oldest = file
print oldest
with open(fromdir + "/" + oldest,'r') as f:
    output = f.read()
print output

headers ={'data': output,
         'User-Agent': 'Mozilla/5.0'}


from urllib2 import Request, urlopen, URLError, HTTPError
#data = urllib.urlencode(values)
#req = urllib2.Request(url, data, headers)

req = Request(url, "Data", headers)
try:
    response = urlopen(req)
except HTTPError as e:
    print 'The server couldn\'t fulfill the request.'
    print 'Error code: ', e.code
except URLError as e:
    print 'We failed to reach a server.'
    print 'Reason: ', e.reason
else:
    print "all ok"
    print response 
    #shutil.move(fromdir + '/' + oldest, todir)

Tags: pathinimporturlhomedatatimeos