How to use name_url method in avocado

Best Python code snippet using avocado_python

main.py

Source:main.py Github

copy

Full Screen

1import requests2from flask import Flask, jsonify, request, redirect3app = Flask(__name__)4app.config['JSON_SORT_KEYS'] = False5# las siguientes rutas corresponden a la pokeapi6@app.errorhandler(404)7def pageNotfound(e):8 return jsonify({"Error ": "la pagina no existe, ingresa una direccion valida"})9@app.errorhandler(405)10def pageNotfound(e):11 return jsonify({"Error ": "verifica el tipo de metodo"})12@app.route('/')13def homeRESTAPI():14 return """<h1>Bienvenido</h1> 15 <h2>Contamos con 4 endpoins funcionales y uno de ayuda para tus peticiones</h2>16 <h3>/all - GET </h3>17 <h3>/pokedex - POST y GET </h3>18 <h3>/pokemon - POST y GET </h3>19 <h3>/type - POST y GET </h3>20 <h3>/restdoc</h3>21 <p> Recuerda utilizar un restclient para las peticiones POST </p>22"""23@app.route('/restdoc')24def docRESTAPI():25 return redirect("https://documenter.getpostman.com/view/18771793/VUjSENtP")26@app.route('/all', methods=['GET'])27def allPokemonGET():28 """Retorna todos los pokemon"""29 data = []30 name_url = "https://pokeapi.co/api/v2/pokemon?limit=151"31 while True:32 resp = requests.get(name_url)33 json = resp.json()34 data.extend(json.get('results', []))35 name_url = json.get('next')36 if not name_url:37 break38 return jsonify(data)39@app.route('/pokedex', methods=['POST'])40def pokedex():41 """Generar respuesta JSON mediante envio de solicitud mediante postman por el body"""42 if request.method == 'POST':43 name = request.json['name']44 name_url = f"https://pokeapi.co/api/v2/pokedex/{name}"45 result = requests.get(name_url)46 resultJson = result.json()47 return jsonify(resultJson)48@app.route('/pokedex/<string:name>', methods=['GET'])49def pokedexGET(name):50 """Generar respuesta JSON mediante envio de parametros"""51 if request.method == 'GET':52 name_url = f"https://pokeapi.co/api/v2/pokedex/{name}"53 result = requests.get(name_url)54 resultJson = result.json()55 return jsonify(resultJson)56@app.route('/pokemon', methods=['POST'])57def pokemonName():58 """Generar respuesta JSON mediante envio de solicitud mediante postman por el body"""59 if request.method == 'POST':60 name = request.json['name']61 name_url = f"https://pokeapi.co/api/v2/pokemon/{name}"62 result = requests.get(name_url)63 resultJson = result.json()64 return jsonify({65 "id": resultJson['id'],66 "name": resultJson['name'],67 "types": resultJson['types'],68 "stats": resultJson['stats'],69 "game_indices": resultJson['game_indices']})70@app.route('/pokemon/<string:name>', methods=['GET'])71def pokemonNameGET(name):72 """Para buscar un pokemon en especifico"""73 name_url = f"https://pokeapi.co/api/v2/pokemon/{name}"74 result = requests.get(name_url)75 resultJson = result.json()76 return jsonify({77 "id": resultJson['id'],78 "name": resultJson['name'],79 "types": resultJson['types'],80 "stats": resultJson['stats'],81 "game_indices": resultJson['game_indices']82 })83@app.route('/type', methods=['POST'])84def pokemonType():85 """Para buscar un typo pokemon en especifico"""86 if request.method == 'POST':87 type = request.json['type']88 name_url = f"https://pokeapi.co/api/v2/type/{type}"89 result = requests.get(name_url)90 resultJson = result.json()91 return jsonify({92 "id": resultJson['id'],93 "name": resultJson['name'],94 "game_indices": resultJson['game_indices']95 })96@app.route('/type/<string:nametype>', methods=['GET'])97def pokemonTypeGET(nametype):98 """Para buscar un pokemon en especifico"""99 name_url = f"https://pokeapi.co/api/v2/type/{nametype}"100 result = requests.get(name_url)101 resultJson = result.json()102 return jsonify({103 "id": resultJson['id'],104 "name": resultJson['name'],105 "game_indices": resultJson['game_indices']106 })107if __name__ == '__main__':...

Full Screen

Full Screen

write_read_url.py

Source:write_read_url.py Github

copy

Full Screen

1 #-*- coding:utf-8 -*-2import os,sys 3import json4import re5parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))6# print("write_read_url.py:", parentdir)7def w_r_url(source,model,url={}):8 name_url = {}9 if model == 1:10 #1表示读取函数11 if source == '360百科':12 with open(os.path.join(parentdir,'start_end\\bk360_name_url'), 'r', encoding='utf-8') as f:13 name_url = f.read()14 if name_url.startswith(u'\ufeff'):15 #忽略掉BOM字符16 name_url = name_url.encode('utf8')[3:].decode('utf8')17 name_url = re.sub('\'','"',name_url)18 name_url = json.loads(name_url, strict=False)19 elif source == '搜狗百科':20 with open(os.path.join(parentdir,'start_end\\sougou_name_url'), 'r', encoding='utf-8') as f:21 name_url = f.read()22 if name_url.startswith(u'\ufeff'):23 #忽略掉BOM字符24 name_url = name_url.encode('utf8')[3:].decode('utf8')25 name_url = re.sub('\'', '"', name_url)26 name_url = json.loads(name_url, strict=False)27 elif source == '互动百科':28 with open(os.path.join(parentdir,'start_end\\hudong_name_url'), 'r', encoding='utf-8') as f:29 name_url = f.read()30 if name_url.startswith(u'\ufeff'):31 #忽略掉BOM字符32 name_url = name_url.encode('utf8')[3:].decode('utf8')33 name_url = re.sub('\'', '"', name_url)34 name_url = json.loads(name_url, strict=False)35 elif source == '百度百科':36 with open(os.path.join(parentdir,'start_end\\baidu_name_url'), 'r', encoding='utf-8') as f:37 name_url = f.read()38 if name_url.startswith(u'\ufeff'):39 #忽略掉BOM字符40 name_url = name_url.encode('utf8')[3:].decode('utf8')41 name_url = re.sub('\'', '"', name_url)42 name_url = json.loads(name_url, strict=False)43 return (name_url)44 if model == 2:45 #表示写入函数46 if source == '360百科':47 with open(os.path.join(parentdir,'start_end\\bk360_name_url'), 'a+', encoding='utf-8') as f:48 f.truncate(0)49 f.write(str(url))50 elif source == '搜狗百科':51 with open(os.path.join(parentdir,'start_end\\sougou_name_url'), 'a+', encoding='utf-8') as f:52 f.truncate(0)...

Full Screen

Full Screen

00lagou_spider.py

Source:00lagou_spider.py Github

copy

Full Screen

1import requests2import json3import os4from lxml import etree5if os.path.exists('lagouwang.txt'):6 os.remove('lagouwang.txt')7def get_ip():8 url = 'http://www.zhuhaizhuochi.cn/Tools/proxyIP.ashx?OrderNumber=71e5cbfa913eee46e089accebeafd556&poolIndex=49233&cache=1&qty=1'9 req = requests.get(url)10 ip = req.content.decode('utf-8', 'ignore')11 return ip12def get_home_page(name_url):13 headers = {14 'Host': 'www.lagou.com',15 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'16 }17 name_url = json.loads(name_url)18 # print(name_url)19 start_url = name_url['url']20 name = name_url['name']21 flog = 022 for page in range(1, 2):23 print('正在写入关于{}的第{}页信息···'.format(name, page))24 ip = get_ip()25 print(ip)26 proxies = {'http': ip}27 end_url = str(page) + '/?filterOption=' + str(page)28 find_url = start_url + end_url29 response = requests.get(url=find_url, headers=headers, proxies=proxies)30 html = response.text31 data = etree.HTML(html)32 items = data.xpath('//*[@id="s_position_list"]/ul/li')33 for item in items:34 name = item.xpath('./div[1]/div[1]/div[1]/a//text()')35 # //*[@id="s_position_list"]/ul/li[1]/div[1]/div[1]/div[1]/a36 name = ''.join(name).replace('\n', '').replace(' ', '')37 money = item.xpath('./div[1]/div[1]/div[2]/div//text()')38 money = ''.join(money).replace('\n', '').replace(' ', '').replace('经验', '/')39 tag = item.xpath('./div[2]/div[1]//text()')40 tag = ''.join(tag).replace('\n', '、').replace(' ', '')41 company = item.xpath('./div[1]/div[2]/div[1]/a/text()')42 company = ''.join(company)43 info = item.xpath('./div[1]/div[2]/div[2]/text()')44 info = ''.join(info).replace('\n', '').replace(' ', '')45 word = item.xpath('./div[2]/div[2]/text()')46 word = ''.join(word)47 print(name+money+tag+company+info+word)48 with open('lagouwang.txt', 'a', encoding='utf-8')as f:49 f.write(name+money+tag+company+info+word+'\n')50def main():51 with open('拉钩网-首页.txt', 'r', encoding='utf-8') as f:52 lst_name_url = f.readlines()53 for name_url in lst_name_url:54 get_home_page(name_url)55if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful