reply.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from selenium.webdriver.common.action_chains import ActionChains
  2. from selenium.common.exceptions import NoSuchElementException, TimeoutException
  3. from selenium import webdriver
  4. import random
  5. import time
  6. def reply(driver, url):
  7. while True:
  8. reply_page_url = get_reply_page_url(driver, url)
  9. try:
  10. driver.get(reply_page_url)
  11. except TimeoutException:
  12. continue
  13. else:
  14. content = get_reply_content(driver)
  15. try:
  16. temp_driver = webdriver.Chrome()
  17. temp_driver.get('http://fanyi.youdao.com/')
  18. input_content = temp_driver.find_element_by_id('inputOriginal')
  19. input_content.send_keys(content)
  20. time.sleep(3)
  21. content = temp_driver.find_element_by_xpath("//div[@id='transTarget']/p/span").text
  22. input_delete = temp_driver.find_element_by_id('inputDelete')
  23. ActionChains(temp_driver).move_to_element(input_delete).click().perform()
  24. input_content.send_keys(content)
  25. time.sleep(3)
  26. content = temp_driver.find_element_by_xpath("//div[@id='transTarget']/p/span").text
  27. temp_driver.quit()
  28. except Exception as e:
  29. print(e)
  30. if not content == '#':
  31. if start_reply(driver, content):
  32. break
  33. time.sleep(2)
  34. # 进行回复动作
  35. def start_reply(driver, content):
  36. try:
  37. message = driver.find_element_by_id('vmessage')
  38. except NoSuchElementException:
  39. return False
  40. else:
  41. ActionChains(driver).move_to_element(message).perform()
  42. time.sleep(6)
  43. ActionChains(driver).double_click(message).perform()
  44. time.sleep(3)
  45. message.send_keys(content)
  46. print(content)
  47. time.sleep(1)
  48. element = driver.find_element_by_id('vreplysubmit')
  49. ActionChains(driver).move_to_element(element).click().perform()
  50. return True
  51. # 读取从上往下第二条评论的内容,并返回
  52. def get_reply_content(driver):
  53. i = 4
  54. while i >= 0:
  55. r = random.randint(3, 12)
  56. r = str(r)
  57. try:
  58. element = driver.find_element_by_xpath(
  59. "//div[@id='postlist']/div[" + r + "]/table/tbody/tr/td[2]/div[2]/div/div/table/tbody/tr/td")
  60. except NoSuchElementException:
  61. i = i - 1
  62. else:
  63. content = element.text
  64. if '发表于' not in content and '本贴最后由' not in content:
  65. return content
  66. else:
  67. i = i - 1
  68. return '#'
  69. # 取得mod发布页面的最后一个页面的url
  70. def get_reply_page_url(driver, url):
  71. driver.get(url)
  72. r = random.randint(0, 24)
  73. r = str(r)
  74. element = driver.find_element_by_xpath("//form[@id='moderate']/table/tbody[last()-" + r + "]/tr/th/a[3]")
  75. return element.get_attribute('href')