当前位置:   article > 正文

爬虫——有道云翻译_python 有道翻译

python 有道翻译

废话不多说直接上代码

固定文本内容

  1. import time
  2. from selenium import webdriver
  3. from selenium.common.exceptions import NoSuchElementException, TimeoutException
  4. from selenium.webdriver.common.by import By
  5. from selenium.webdriver.support.ui import WebDriverWait
  6. from selenium.webdriver.support import expected_conditions as EC
  7. driver = webdriver.Chrome()
  8. # driver = webdriver.Chrome()
  9. driver.get("https://fanyi.baidu.com/")
  10. driver.find_element(By.CLASS_NAME, "f9WVaz_4").click()
  11. text_to_input = """Sure! Here’s the classic fairy tale “Cinderella” in English:
  12. Once upon a time, there was a kind and beautiful girl named Cinderella. Her father married a wicked stepmother, who brought along two selfish and arrogant stepsisters.
  13. From that moment on, Cinderella became the household servant, doing countless chores every day, while her stepmother and stepsisters treated her cruelly.
  14. One day, the king announced a grand ball, inviting all the young maidens in the kingdom. Cinderella longed to attend, but her stepmother forbade her.
  15. Cinderella cried in disappointment, but then a fairy godmother appeared and helped her transform into a beautiful ball gown and provided her with a pair of glass slippers.
  16. Dressed in her magnificent attire, Cinderella went to the ball. There, the prince was captivated by her beauty and kindness.
  17. Unfortunately, time waits for no one, and when the clock struck midnight, Cinderella hurriedly left, leaving behind one of her glass slippers.
  18. The prince searched the kingdom, and only Cinderella’s foot could fit into the glass slipper. Eventually, Cinderella put on the glass slipper and became the prince’s princess, living happily ever after.
  19. From then on, Cinderella’s kindness and courage were remembered by all who knew her.
  20. """
  21. # batch_size = 100 # 每个批次的文本数量
  22. # for i in range(0, len(text_to_input), batch_size):
  23. # batch_text = text_to_input[i:i + batch_size]
  24. # try:
  25. # div_with_slate_node = driver.find_element(By.CSS_SELECTOR, "div[data-slate-node='element']")
  26. # div_with_slate_node.send_keys(batch_text)
  27. #
  28. # # 使用显式等待等待文本输入完成
  29. # WebDriverWait(driver, 20).until(
  30. # EC.text_to_be_present_in_element((By.CSS_SELECTOR, "div[data-slate-node='element']"), batch_text))
  31. # except NoSuchElementException as e:
  32. # print("未找到指定的 div 元素:", e)
  33. div_with_slate_node = driver.find_element(By.CSS_SELECTOR, "div[data-slate-node='element']")
  34. div_with_slate_node.send_keys(text_to_input)
  35. # WebDriverWait(driver, 13).until(
  36. # EC.text_to_be_present_in_element((By.CSS_SELECTOR, "div[data-slate-node='element']"), batch_text))
  37. # WebDriverWait(driver, 5).until(
  38. # EC.visibility_of_element_located((By.CSS_SELECTOR, "div[data-slate-node='element']")))
  39. # time.sleep(20)
  40. timeout = 20
  41. try:
  42. # 使用 driver.find_element 定位指定的元素
  43. div_element = WebDriverWait(driver, timeout).until(
  44. EC.presence_of_element_located((By.CLASS_NAME, "KzfYYzYR"))
  45. )
  46. span_elements = div_element.find_elements(By.CSS_SELECTOR, ".nbyIWSn1 span")
  47. # 提取每个span元素的文本内容
  48. for span_element in span_elements:
  49. text_content = span_element.text
  50. print(text_content)
  51. except TimeoutException:
  52. print("超时:在{}秒内未能成功获取数据".format(timeout))
  53. # 关闭浏览器
  54. # driver.quit()

图形输入内容:

  1. import random
  2. from tkinter import *
  3. from tkinter.ttk import *
  4. from tkinter import ttk
  5. import tkinter as tk
  6. from selenium import webdriver
  7. from selenium.webdriver.common.by import By
  8. import time
  9. from selenium import webdriver
  10. from selenium.common.exceptions import NoSuchElementException
  11. from selenium.webdriver.common.by import By
  12. from selenium.webdriver.support.ui import WebDriverWait
  13. from selenium.webdriver.support import expected_conditions as EC
  14. from selenium.webdriver.chrome.options import Options
  15. import tkinter.messagebox as mb
  16. class WinGUIFy(Tk):
  17. def __init__(self):
  18. super().__init__()
  19. self.__win()
  20. self.tk_label_lwt9kgap = self.__tk_label_lwt9kgap(self)
  21. self.tk_input_lwt9lqdw = self.__tk_input_lwt9lqdw(self)
  22. self.tk_input_lwt9n2k3 = self.__tk_input_lwt9n2k3(self)
  23. self.tk_label_lwt9o4s7 = self.__tk_label_lwt9o4s7(self)
  24. self.tk_label_lwt9oj39 = self.__tk_label_lwt9oj39(self)
  25. self.tk_label_lwt9ta6h = self.__tk_label_lwt9ta6h(self)
  26. def File_like(self, even):
  27. try:
  28. chrome_options = Options()
  29. chrome_options.add_argument('--headless') # 无界面模式
  30. chrome_options.add_argument('--disable-gpu') # 禁用GPU加速
  31. driver = webdriver.Chrome(options=chrome_options)
  32. # driver = webdriver.Chrome()
  33. driver.get("https://fanyi.youdao.com/index.html#/")
  34. time.sleep(2)
  35. try:
  36. driver.find_element(By.CLASS_NAME,"close").click()
  37. except Exception as e:
  38. print("继续..")
  39. # 定位到包含文本为“翻译”的 span 元素的父元素 div
  40. button_element = driver.find_element(By.XPATH, "//div[@class='tab-item active color_text_1'][span='翻译']")
  41. # 点击按钮
  42. button_element.click()
  43. # 获取到文本框的值
  44. content = self.text_box.get("1.0", "end-1c")
  45. input_element = driver.find_element(By.ID, "js_fanyi_input")
  46. input_element.send_keys(content)
  47. time.sleep(4)
  48. text_content = driver.execute_script(
  49. "return document.getElementById('js_fanyi_output_resultOutput').textContent;")
  50. print(text_content)
  51. self.text_name.config(state="normal")
  52. self.text_name.delete('1.0', tk.END)
  53. self.text_name.insert(tk.END, text_content)
  54. self.text_name.config(state="disabled")
  55. # 关闭浏览器
  56. driver.quit()
  57. except Exception as e:
  58. # 弹框提示网络不流畅
  59. mb.showerror("Error", "网络不流畅,请尝试更换网络!")
  60. def __win(self):
  61. self.title("Tkinter布局助手")
  62. # 设置窗口大小、居中
  63. width = 900
  64. height = 700
  65. screenwidth = self.winfo_screenwidth()
  66. screenheight = self.winfo_screenheight()
  67. geometry = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
  68. self.geometry(geometry)
  69. self.resizable(width=False, height=False)
  70. def scrollbar_autohide(self, vbar, hbar, widget):
  71. """自动隐藏滚动条"""
  72. def show():
  73. if vbar: vbar.lift(widget)
  74. if hbar: hbar.lift(widget)
  75. def hide():
  76. if vbar: vbar.lower(widget)
  77. if hbar: hbar.lower(widget)
  78. hide()
  79. widget.bind("<Enter>", lambda e: show())
  80. if vbar: vbar.bind("<Enter>", lambda e: show())
  81. if vbar: vbar.bind("<Leave>", lambda e: hide())
  82. if hbar: hbar.bind("<Enter>", lambda e: show())
  83. if hbar: hbar.bind("<Leave>", lambda e: hide())
  84. widget.bind("<Leave>", lambda e: hide())
  85. def v_scrollbar(self, vbar, widget, x, y, w, h, pw, ph):
  86. widget.configure(yscrollcommand=vbar.set)
  87. vbar.config(command=widget.yview)
  88. vbar.place(relx=(w + x) / pw, rely=y / ph, relheight=h / ph, anchor='ne')
  89. def h_scrollbar(self, hbar, widget, x, y, w, h, pw, ph):
  90. widget.configure(xscrollcommand=hbar.set)
  91. hbar.config(command=widget.xview)
  92. hbar.place(relx=x / pw, rely=(y + h) / ph, relwidth=w / pw, anchor='sw')
  93. def create_bar(self, master, widget, is_vbar, is_hbar, x, y, w, h, pw, ph):
  94. vbar, hbar = None, None
  95. if is_vbar:
  96. vbar = Scrollbar(master)
  97. self.v_scrollbar(vbar, widget, x, y, w, h, pw, ph)
  98. if is_hbar:
  99. hbar = Scrollbar(master, orient="horizontal")
  100. self.h_scrollbar(hbar, widget, x, y, w, h, pw, ph)
  101. self.scrollbar_autohide(vbar, hbar, widget)
  102. def __tk_label_lwt9kgap(self, parent):
  103. label = Label(parent, text="翻译中心", anchor="center", )
  104. label.place(x=319, y=29, width=277, height=30)
  105. return label
  106. # 输入
  107. def __tk_input_lwt9lqdw(self, parent):
  108. self.text_box = tk.Text(parent, )
  109. self.text_box.place(x=21, y=110, width=385, height=456)
  110. self.text_box.bind("<Return>", self.File_like)
  111. return self.text_box
  112. def __tk_input_lwt9n2k3(self, parent):
  113. self.text_name = tk.Text(parent, state="disabled")
  114. self.text_name.place(x=480, y=107, width=407, height=459)
  115. return self.text_name
  116. def __tk_label_lwt9o4s7(self, parent):
  117. label = Label(parent, text="内容区", anchor="center", )
  118. label.place(x=159, y=69, width=121, height=30)
  119. return label
  120. def __tk_label_lwt9oj39(self, parent):
  121. label = Label(parent, text="翻译区", anchor="center", )
  122. label.place(x=656, y=65, width=80, height=30)
  123. return label
  124. def __tk_label_lwt9ta6h(self, parent):
  125. label = Label(parent, text="回\n车\n执\n行\n", anchor="center", )
  126. label.place(x=417, y=105, width=50, height=235)
  127. return label
  128. class Win(WinGUIFy):
  129. def __init__(self, controller):
  130. self.ctl = controller
  131. super().__init__()
  132. self.__event_bind()
  133. self.__style_config()
  134. self.ctl.init(self)
  135. def __event_bind(self):
  136. pass
  137. def __style_config(self):
  138. pass
  139. if __name__ == "__main__":
  140. win = WinGUIFy()
  141. win.mainloop()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/855735
推荐阅读
相关标签
  

闽ICP备14008679号