Python+selenium 谷歌翻译

from selenium import webdriver
import time

"""
chrome_driver_path: 修改为自己的chromedriver所在路径,最好是绝对路径,
interval: 如果报错,请延长等待时间,等待下翻译结果的返回
debug: 是否输出Debug内容
"""
chrome_driver_path = "/home/hyh/GoogleDriver/chromedriver"
interval = 3
debug = True


def translate_one_word(_text, src, dest):
url = "https://translate.google.cn/?sl=" + src + "&tl=" + dest + "&op=translate"

options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--headless")
options.add_argument('--disable-infobars')
options.add_argument('--blink-settings=imagesEnabled=false')
driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)
driver.get(url)
if debug:
print("---------------------------")
print("成功进入页面:", driver.title)
time.sleep(interval)
input_element = driver.find_element_by_tag_name('textArea')
input_element.send_keys(text)
time.sleep(interval)
if debug:
print("开始翻译文字:", _text)
result_elements = driver.find_elements_by_tag_name('span')
result = result_elements[87].text
if debug:
print("开始输出结果:", result)
time.sleep(interval)
driver.close()
if debug:
print("成功关闭页面")
print("---------------------------")
return result


def translate_one_list(_texts, src, dest):
url = "https://translate.google.cn/?sl=" + src + "&tl=" + dest + "&op=translate"

options = webdriver.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--headless")
options.add_argument('--disable-infobars')
options.add_argument('--blink-settings=imagesEnabled=false')
driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)
driver.get(url)
if debug:
print("---------------------------")
print("成功进入页面:", driver.title)
time.sleep(interval)

input_element = driver.find_element_by_tag_name('textArea')
results = []
for _text in _texts:
input_element.clear()
input_element.send_keys(_text)
time.sleep(interval)
if debug:
print("开始翻译文字:", _text)
result_elements = driver.find_elements_by_tag_name('span')
result = result_elements[87].text
if debug:
print("开始输出结果:", result)
results.append(result)
time.sleep(interval)
time.sleep(interval)
driver.close()
if debug:
print("成功关闭页面")
print("---------------------------")
return results


if __name__ == '__main__':
text = "hello world"
output = translate_one_word(text, src='en', dest='zh-CN')
print(output)

# text = ["hello world", "how are you"]
# output = translate_one_list(text, src='en', dest='zh-CN')
# print(output)