How to use translateResult method in autotest

Best Python code snippet using autotest_python

getweatherinfo.py

Source:getweatherinfo.py Github

copy

Full Screen

1# encoding: utf-82#特别注意,下面两行代码是专门为了Linux服务器上在不同目录文件中找到publicTool中的文件而写的,即在Linux环境下增加系统变量,不要忘记!!!3import os4import sys5import random6sys.path.append("/usr/pythonprojects/publicTools")7from config import EmailAddressEnum #配置文件8import public #公共方法文件9from selenium import webdriver #打开浏览器文件10from selenium.webdriver.common.desired_capabilities import DesiredCapabilities #伪装模块11#显式等待12from selenium.webdriver.support.wait import WebDriverWait13from selenium.webdriver.support import expected_conditions as EC14from selenium.webdriver.common.by import By15from sendEmailTools import SendMailClass #发送邮件文件16import datetime17from datetime import datetime18import time19from time import sleep20from apscheduler.schedulers.blocking import BlockingScheduler21#进行翻译转化过滤22def getTranslateresult(str,tolanguagetype):23 #不是中文的话就需要进行翻译24 if tolanguagetype != "zh":25 return public.TranslateLanguage(str,totype=tolanguagetype)26 else:27 return str28#参数定义,传进来的参数为一个数组和一个日期索引,数组中每一个元素为一个城市字典,字典包含城市的代码/名称以及对应要发送的邮件接受者地址数组29#执行函数时,循环每一个城市字典,发送完毕之后再次循环下一个城市字典30#日期索引dayindex代表的是发送今天的还是明天的还是后几天的天气,0代表今天的天气情况,数值为0~6,默认为明天的天气情况,即dayindex = 131def getweatherinfomsg(CityArr,dayindex=1):32 #循环每一个城市,给该城市下对应的邮件接收者发送对应日期的天气预报33 for cityindex, citydic in enumerate(CityArr):34 #城市编码/名称35 city = citydic["city"]36 #tolanguage 目标语言类型37 tolanguagetype = citydic["tolanguage"] #需要转化的目标语言类型38 #该城市对应的邮件接收者数组39 toemailaddressArr = citydic["toemailaddressArr"]40 # 因为米胖的接口设计,如果是一线城市的话可以直接输入城市全程的拼音作为拼接参数进行接口请求,如果是其他城市则进行城市编码拼接请求41 # 所以此处做一个判断,如果传过来的参数带有数字,则说明是城市编码,这时完整链接为 https://weather.mipang.com/tianqi- + 城市编码42 # 如果参数内不含数字,则完整链接为 https://weather.mipang.com/ + 城市全称拼音43 url = "https://weather.mipang.com/tianqi-" + str(city) if public.hasNumbers(44 str(city)) else "https://weather.mipang.com/" + str(city)45 # 首先将DesiredCapabilities转换为一个字典,方便添加键值对46 dcap = dict(DesiredCapabilities.PHANTOMJS)47 # 然后添加一个浏览器标识的键值对:48 dcap['phantomjs.page.settings.userAgent'] = (random.choice(public.User_Agent_List))49 # 因为是js加载的,所以使用phantomjs来加载 注意此处需要增加这两个参数,否则有些网站获取不到网页源码!!!50 browser = webdriver.PhantomJS(desired_capabilities=dcap,51 service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1',52 '--webdriver-loglevel=NONE'])53 # 使用while循环54 i = 055 while i < 10:56 try:57 print ('开始今日第' + str(i) + '次抓取网页数据……')58 #browser.implicitly_wait(60) # 隐式等待,最长等60秒59 print "开始抓取网页的时间为:" + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))60 browser.get(url)61 sleep(10) # 强制等待10秒再执行下一步62 # 开始解析数据:63 print "开始解析数据的时间为:" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))64 # 城市名称+天气两个字:65 cwrname = browser.find_element_by_css_selector(".page-title").text66 # 一周的天气信息67 weatherinfos = browser.find_elements_by_css_selector(".box1 div.item")68 # 天气概况69 weathersimpledes = browser.find_element_by_css_selector("div.sidebar div.br1 div.row1").text70 # 明天的穿衣建议71 dresssuggest = browser.find_element_by_css_selector(".box1 div.chuanyi").text # 穿衣建议 只有明天才有穿衣建议72 # 数组中元素按照顺序解释为从今天到往后的7天内的天气信息73 AweekWeatherInfoArr = []74 for weatherinfo in weatherinfos:75 # 每一个天气信息中包含6个div,分别代表日期 温度 天气图标 天气描述 风的来向 风级76 # 日期(包含week和day)77 week = weatherinfo.find_element_by_css_selector("div.t1 div.week").text # eg: 今天 明天 星期一 星期二 ……78 date = weatherinfo.find_element_by_css_selector("div.t1 div.day").text # eg: 10月21日79 # 温度:80 lowtemp = weatherinfo.find_element_by_css_selector("div.t2 span.temp1").text # eg: 2081 hightemp = weatherinfo.find_element_by_css_selector("div.t2 span.temp2").text # eg: 28℃82 # 天气图标83 weathericonUrl = weatherinfo.find_element_by_css_selector("div.t3 img").get_attribute("src")84 # eg: https://tq-s.malmam.com/images/icon/256/02.png85 # 天气描述86 weatherdes = weatherinfo.find_element_by_css_selector("div.t4").text # eg: 阴转小雨87 # 风向图标88 windiconUrl = weatherinfo.find_element_by_css_selector("div.t5 img").get_attribute("src")89 # eg: https://tq-s.malmam.com/images/direct/3.png90 # 风向及级别描述91 winddes = weatherinfo.find_element_by_css_selector("div.t6").text # eg: 东南风3级92 weatherdic = {93 "week": week, # eg:今天 明天 星期一 星期二 ……94 "date": date, # eg:10月21日95 "lowtemp": lowtemp, # eg:2096 "hightemp": hightemp, # eg:28℃97 "weathericonUrl": weathericonUrl, # eg:https://tq-s.malmam.com/images/icon/256/02.png98 "weatherdes": weatherdes, # eg:阴转小雨99 "windiconUrl": windiconUrl, # eg:https://tq-s.malmam.com/images/direct/3.png100 "winddes": winddes # eg:东南风101 }102 # 加入到数组中103 AweekWeatherInfoArr.append(weatherdic)104 # 取出相应日期对应的天气情况 0~6代表从今天开始的往后7天105 # 取数组中第一个天气字典,代表的是今天的天气106 # 取数组中第二个天气字典,代表的是明天的天气 ……以此类推107 weatherinfodic = AweekWeatherInfoArr[int(dayindex)]108 # 发送指定日期的天气情况109 week = weatherinfodic["week"] # eg:今天 明天 星期一 星期二 ……110 date = weatherinfodic["date"] # eg:10月21日111 lowtemp = weatherinfodic["lowtemp"] # eg:20112 hightemp = weatherinfodic["hightemp"] # eg:28℃113 weathericonUrl = weatherinfodic["weathericonUrl"] # eg:https://tq-s.malmam.com/images/icon/256/02.png114 weatherdes = weatherinfodic["weatherdes"] # eg:阴转小雨115 windiconUrl = weatherinfodic["windiconUrl"] # eg:https://tq-s.malmam.com/images/direct/3.png116 winddes = weatherinfodic["winddes"] # eg:东南风3级117 print("抓取第" + str(cityindex) + "个城市的天气信息成功:" + cwrname + week + " " + date + " " + lowtemp + " " + hightemp + " "+ weathericonUrl + " " + weatherdes + " " + windiconUrl + " " + winddes + " ")118 # 发送邮件119 sendmail = SendMailClass()120 # 根据参数tolanguage来判断是否需要进行翻译,如果需要进行翻译则规定目标文本类型121 # 小海哥问候语122 timestr = datetime.strftime(datetime.now(), '%Y/%m/%d %H:%M:%S')123 content1 = "<h4 style='color: orange;font-weight: 100'>" + getTranslateresult(124 "嗨,我亲爱的你,此刻是 " + ":" + " ", tolanguagetype) + timestr + "</h4>"125 # 城市天气名字字样126 cityweathername = cwrname.strip("天气") # 北京127 content2 = "<span style='color: black;font-size:2rem'>" + getTranslateresult(cityweathername,128 tolanguagetype) + " " + "</span>"129 # 日期称呼130 datename = week if dayindex != 2 else "后天" # 设置日期称呼,暂时设置为第一二三天称呼为今天 明天 后天 其他的称呼为星期几131 content3 = getTranslateresult(datename + "是" + date + ",", tolanguagetype) + " "132 # 温度显示133 content4 = getTranslateresult("温度为:",134 tolanguagetype) + "<span style='color: orange;font-weight: 200;font-size=x-large'>" + lowtemp + "~" + hightemp + "</span>" + " "135 # 天气描述136 content5 = getTranslateresult(weatherdes,137 tolanguagetype) + "<img src='cid:image0' width:30px height=30px>" + " "138 # 风向描述139 content6 = getTranslateresult(winddes, tolanguagetype) + "<img src='cid:image1'>" + " "140 # 穿衣建议141 content7 = "<span style='color: orange;font-weight: 200'>" + getTranslateresult(dresssuggest,142 tolanguagetype) + "</span>"143 # 关于极端温度的提示 此处设置为最低温度低于-8℃时提醒温度较低,最高温度高于35℃时提醒气温过高144 content8 = ""145 lowtempint = float(lowtemp)146 hightempint = float(hightemp.strip("℃"))147 if lowtempint < -8:148 content8 = "<span style='color: #1C3B6E;font-weight: 200'>" + "————" + getTranslateresult(149 "天气虽冷,我心火热", tolanguagetype) + "</span>"150 if hightempint > 35:151 content8 = "<span style='color: #FA331C;font-weight: 200'>" + "————" + getTranslateresult(152 "天气虽热,我心似冰", tolanguagetype) + "</span>"153 # 天气简述:(单独成段落展示)154 content9 = "<p style='color:darkgray;font-weight: 100;font-size:small'>" + getTranslateresult(155 weathersimpledes + "(如文中图片未正常显示,请信任该发件人)", tolanguagetype) + "--" + getTranslateresult(156 "时刻运行,只为守护你的每一度", tolanguagetype) + "</p>"157 totalhtml = content1 + content2 + content3 + content4 + content5 + content6 + content7 + content8 + content9158 totalimgs = [weathericonUrl, windiconUrl]159 totalsubject = getTranslateresult("嗨," + week,160 tolanguagetype) + " " + lowtemp + "~" + hightemp + " " + getTranslateresult(161 dresssuggest, tolanguagetype)162 sendmail.sendmail(163 toemailaddressArr,164 totalhtml,165 emailimgArr=totalimgs,166 emailsubject=totalsubject,167 fromNickname=getTranslateresult("小海哥天气管家", tolanguagetype),168 emailfooter="——" + getTranslateresult("小海哥天气管家", tolanguagetype),169 # emailbodybgimg=bodybgimg170 )171 # 每发送成功一组就进行一次日志记录172 print("第" + str(cityindex) + "组城市天气邮件已经发送,发送时间:" + datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))173 #成功之后结束退出本次循环174 print ('第'+str(cityindex)+'组城市程序运行完毕')175 break176 except Exception as e:177 if e != KeyboardInterrupt:178 i += 1179 # 达到10次的尝试次数之后return掉整个方法180 if i == 10:181 print ("该城市今日尝试次数已经达到10次,将结束该城市的程序运行")182 continue183 print ('第'+str(cityindex)+'个城市程序运行完毕,将自动关闭浏览器!')184 # 抓取完数据之后将Phantom浏览器关闭!非常重要,否则会导致程序永远不会停止185 browser.quit()186 print("所有城市天气邮件已经发送完毕,发送时间:" + datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))187#发送明天的天气预报188def sendthetomorrowinfo():189 #从本地csv文件中获取到最新的接收人数组 注意此处要把本地的相对路径转换为Linux上的绝对路径190 ABSPATH = os.path.abspath(sys.argv[0])191 ABSPATH = os.path.dirname(ABSPATH) + "/toUserList.csv"192 toUserlist = public.returndatafromreadcsvfile(ABSPATH)193 toUserlistArr = []#发送人字典数组194 for User in toUserlist:195 city = User["city"] #城市名称或者编码196 cityremarkname = User['cityremarkname']#城市昵称197 language = User["language"] #该城市的接收人的语言种类198 EmailAddressStr = User["EmailAddressStr"] #邮件地址(多个以逗号分隔)199 EmailArr = EmailAddressStr.split("-") #同一个城市的接收人邮件地址数组200 toEmailArr = [] #将单纯的邮件地址数组转换为带有昵称和邮件地址的对象字典数组,以便于正确显示收件人信息201 for emailaddress in EmailArr:202 dict = {"nickname":"那个在"+cityremarkname+"的你","address":emailaddress}203 toEmailArr.append(dict)204 #只增加有效的城市名称或者id205 if city:206 # 构建发送对象207 citydict = {208 "city": city,209 "tolanguage": language,210 "toemailaddressArr": toEmailArr211 }212 #将城市字典对象加入到数组中213 toUserlistArr.append(citydict)214#开始发送天气预报215 getweatherinfomsg(216 toUserlistArr,217 dayindex=1218 ) # 发送明天的天气预报219import logging #记录定时任务的运行情况220# log = logging.getLogger('apscheduler.executors.default')221# log.setLevel(logging.INFO) # DEBUG222#223# fmt = logging.Formatter('%(levelname)s:%(name)s:%(message)s')224# h = logging.StreamHandler()225# h.setFormatter(fmt)226# log.addHandler(h)227# 以下为定时任务的代码228sched = BlockingScheduler()229# 通过add_job来添加作业230sched.add_job(sendthetomorrowinfo, 'cron', day_of_week="mon-sun", hour=17, minute=49,second=50,max_instances=100) # 每天下午17:49:50自动发送...

Full Screen

Full Screen

bot.py

Source:bot.py Github

copy

Full Screen

1#!/usr/bin/python32"""This script uses discord api to run a discord bot"""3import os4import googletrans5import discord6import re7from googletrans import Translator8from dotenv import load_dotenv9from discord.ext import commands10load_dotenv()11TOKEN = os.environ.get("DISCORD_TOKEN")12intents = discord.Intents.default()13intents.message_content = True14client = commands.Bot(intents=intents, command_prefix="!")15translator = Translator()16client.remove_command('help')17@client.event18async def on_ready():19 """"prints out to confirm that discord bot is ready"""20 print(str(client.user) + " has connected to Discord!")21@client.command(name="help")22async def help_command(ctx):23 help_string = "```Commands you can run with this bot: \n \n"24 help_string += "!lang -> shows a list of languages can be translated \n\n"25 help_string += "!source `[phrase to translate]` -> gives language source of phrase. \n\n"26 help_string += "!translate `[phrase to translate]` \"[language to translate to(optional)]\" \n\t\t-> translates phrase to chosen language (default is english)```"27 await ctx.send(help_string)28@client.command(name='lang')29async def languages(ctx):30 lang_string = "```"31 for idx, languages in enumerate(googletrans.LANGUAGES):32 lang_string += languages + " = " + googletrans.LANGUAGES[languages]33 if idx % 3 == 0 and idx != 0:34 lang_string += "\n"35 elif idx < len(googletrans.LANGUAGES) - 1:36 lang_string += " | "37 lang_string += "```"38 await ctx.send(lang_string)39@client.command(name='source')40async def source(ctx):41 wordRegex = re.compile("`[\w ]+`", re.UNICODE)42 result = wordRegex.search(ctx.message.content)43 if result != None:44 testPhrase = result.group()45 if testPhrase != None:46 phrase = testPhrase.replace("`", "")47 langSource = translator.detect(phrase).lang48 await ctx.send(ctx.message.author.mention + " The phrase `" + phrase + "` is `" + googletrans.LANGUAGES[langSource] + "`")49 else:50 await ctx.send("Missing argument for `!source` requires phrase to source\nCommand Usage:```!source `[phrase]` ```")51@client.command(name='translate')52async def translate(ctx):53 regexPhrase = re.compile("`[\w ]+`", re.UNICODE)54 regexDest = re.compile("\"[a-zA-Z_ ]+\"")55 testPhrase = regexPhrase.search(ctx.message.content)56 testDest = regexDest.search(ctx.message.content)57 if testPhrase != None:58 phrase = testPhrase.group().replace("`", "")59 if testDest != None:60 destination = testDest.group().replace("\"", "")61 translateResult = translator.translate(phrase, dest=destination)62 await ctx.send(ctx.message.author.mention + " `" + phrase + "` ("+ googletrans.LANGUAGES[translateResult.src] + ") translates to `" + googletrans.LANGUAGES[translateResult.dest] + "` as: `" + translateResult.text + "`")63 else:64 translateResult = translator.translate(phrase)65 await ctx.send(ctx.author.mention + " `" + phrase + "` translates to `" + googletrans.LANGUAGES[translateResult.dest] + "` as: `" + translateResult.text + "`")66 else:67 await ctx.send("Missing argument for `!translate` requires phrase to source\nCommand Usage:```Default:\n!translate `[phrase]`\n\nOptional:\n!translate `[phrase]` \"[translate to language]\"```")68@client.event69async def on_message(message):70 #ignores when author of message is the bot itself71 if message.author == client.user:72 return73 #processes commands that are used in a message74 await client.process_commands(message)...

Full Screen

Full Screen

模拟有道翻译网站翻译.py

Source:模拟有道翻译网站翻译.py Github

copy

Full Screen

1"""21.右键网页or打开开发者工具32.点击Network一栏43.输入英文,翻译。查找post或其他提交数据的网页行为54.查阅General和RequestHeader6"""7import urllib.request8import urllib.parse9import json10import time11while True:12 content = input('请输入需要翻译的内容(输入"q!"退出程序):')13 if content == 'q!':14 break15 # url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'16 url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'17 head = {}18 head['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400'19 data = {}20 data['i'] = content # 不能去!21 data['from'] = 'AUTO'22 data['to'] = 'AUTO'23 data['smartresult'] = 'dict'24 data['client'] = 'fanyideskweb'25 data['salt'] = '1522250255734'26 data['sign'] = '441942c8c597c0b1a51fc12fd0ba794e'27 data['doctype'] = 'json' # 不能去!28 data['version'] = '2.1'29 data['keyfrom'] = 'fanyi.web'30 data['action'] = 'FY_BY_CLICKBUTTION'31 data['typoResult'] = 'false'32 data = urllib.parse.urlencode(data).encode('utf-8')33 req = urllib.request.Request(url, data, head)34 # req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400')35 response = urllib.request.urlopen(req)36 html = response.read().decode('utf-8') # windos下不必要decode37 print(html)38 target = json.loads(html)39 print(target)40 print(target['translateResult'])41 # for i in target['translateResult'][0]:42 # print(i, end='')43 for i in range(len(target['translateResult'][0])):44 print(target['translateResult'][0][i], end='')45 print()46 for i in range(len(target['translateResult'][0])):47 print(target['translateResult'][0][i]['tgt'], end='')48 print()49 # print(target['translateResult'][0][0])50 # print(target['translateResult'][0][0]['tgt'])...

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 autotest 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