Best Python code snippet using autotest_python
getweatherinfo.py
Source:getweatherinfo.py
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èªå¨åé...
bot.py
Source:bot.py
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)...
模拟有道翻译网站翻译.py
Source:模拟有道翻译网站翻译.py
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'])...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!