metting.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # coding:utf-8
  2. from time import sleep
  3. import datetime
  4. import requests
  5. import openpyxl
  6. from selenium import webdriver
  7. # 设置Chrome浏览器选项
  8. from selenium.common import exceptions
  9. from selenium.webdriver.chrome.service import Service
  10. from selenium.webdriver.common.by import By
  11. from selenium.webdriver.support import expected_conditions as EC
  12. from selenium.webdriver.support.wait import WebDriverWait
  13. """
  14. 根据table的id属性和table中的某一个元素定位其在table中的位置
  15. table包括表头,位置坐标都是从1开始算
  16. tableId:table的id属性
  17. queryContent:需要确定位置的内容
  18. """
  19. def get_table_content(driver, tableId, queryContent):
  20. # 按行查询表格的数据,取出的数据是一整行,按空格分隔每一列的数据
  21. table_tr_list = driver.find_element(By.ID, tableId).find_elements(By.TAG_NAME, "tr")
  22. table_list = [] # 存放table数据
  23. for tr in table_tr_list: # 遍历每一个tr
  24. # 将每一个tr的数据根据td查询出来,返回结果为list对象
  25. table_td_list = tr.find_elements(By.TAG_NAME, "td")
  26. row_list = []
  27. print(table_td_list)
  28. for td in table_td_list: # 遍历每一个td
  29. row_list.append(td.text) # 取出表格的数据,并放入行列表里
  30. table_list.append(row_list)
  31. # 循环遍历table数据,确定查询数据的位置
  32. # for i in range(len(table_list)):
  33. # for j in range(len(table_list[i])):
  34. # if queryContent == table_list[i][j]:
  35. # print("%r坐标为(%r,%r)" % (queryContent, i + 1, j + 1))
  36. # 写入文件
  37. def write_excel_xlsx(path, sheet_name, value):
  38. index = len(value) # 列表中所含元组的个数,从而确定写入Excel的行数
  39. # 打开Excel
  40. wb = openpyxl.Workbook()
  41. # wb = load_workbook(path)
  42. sheet = wb.active # 获得一个的工作表
  43. sheet.title = sheet_name
  44. # 设置格式
  45. sheet.column_dimensions['B'].width = 115
  46. # 按行加入
  47. for i in range(index):
  48. sheet.append(value[i])
  49. # 保存文件
  50. print(sheet.values)
  51. wb.save(path)
  52. print("题目写入数据成功!")
  53. def send_file(url, file_path):
  54. with open(file_path, 'rb') as file:
  55. files = {'file': file}
  56. response2 = requests.post(url, files=files)
  57. return response2
  58. def get_element(my_driver, xpaths):
  59. """
  60. 判断是否存在元素并获取元素对象
  61. :param my_driver:
  62. :param xpaths: xpaths表达式
  63. :return: 元素对象或为空
  64. """
  65. try:
  66. target = my_driver.find_element(By.XPATH, xpaths)
  67. except exceptions.NoSuchElementException:
  68. return False
  69. else:
  70. return target
  71. if __name__ == "__main__":
  72. # 创建一个 Chrome WebDriver 实例
  73. options = webdriver.ChromeOptions()
  74. # options.add_argument("headless")
  75. options.add_argument('--headless')
  76. options.add_argument('--disable-gpu')
  77. options.add_argument('--no-sandbox')
  78. options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36')
  79. options.add_argument(" window-size=1920,1080")
  80. # options.add_argument(" window-size=1920,1080")
  81. # s = Service(executable_path='/home/code/python/meeting_probabilities/chromedriver')
  82. s = Service(executable_path='D:\download\chromedriver119-win64\chromedriver.exe')
  83. driver = webdriver.Chrome(service=s, options=options)
  84. # driver.maximize_window()
  85. driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
  86. "source": """
  87. Object.defineProperty(navigator, 'webdriver', {
  88. get: () => undefined
  89. })
  90. """
  91. })
  92. driver.get(
  93. 'https://www.cmegroup.com/markets/interest-rates/cme-fedwatch-tool.html?redirect=/trading/interest-rates/countdown-to-fomc.html')
  94. sleep(2)
  95. agent = driver.execute_script("return navigator.userAgent")
  96. print(agent)
  97. text = driver.find_element(By.XPATH, '//*[@id="page_default_sections"]/div/div/div/div/div/p[1]/span')
  98. print("网页中段,文本内容:")
  99. print(text.text)
  100. btn_pop = get_element(driver, '/html/body/div[4]/div[3]/div/section/span')
  101. if btn_pop:
  102. btn_pop.click()
  103. accept_btn = get_element(driver, '//*[@id="onetrust-accept-btn-handler"]')
  104. if accept_btn:
  105. accept_btn.click()
  106. WebDriverWait(driver, 10).until(
  107. EC.visibility_of_element_located((By.XPATH, '/html/body/main/div/div[4]/div/iframe'))) # iframe是否出现
  108. # page_height = driver.execute_script('return document.documentElement.scrollHeight') # 页面高度
  109. driver.execute_script("window.scrollBy(0,{})".format(600))
  110. driver.switch_to.frame("cmeIframe-jtxelq2f")
  111. sleep(2)
  112. # button = driver.find_element(By.XPATH, '//*[@id="ctl00_MainContent_ucViewControl_IntegratedFedWatchTool_lbPTree"]')
  113. driver.execute_script(
  114. "javascript:__doPostBack('ctl00$MainContent$ucViewControl_IntegratedFedWatchTool$lbPTree','')")
  115. sleep(2)
  116. table = driver.find_element(By.XPATH, '//*[@id="MainContent_pnlContainer"]/div[3]/div/div/table[2]')
  117. table.screenshot(r'meeting.png')
  118. print(table.text)
  119. # 按行查询表格的数据,取出的数据是一整行,按空格分隔每一列的数据
  120. table_tr_list = table.find_elements(By.TAG_NAME, "tr")
  121. table_list = [] # 存放table数据
  122. th_flag = False
  123. title = 'MEETING PROBABILITIES'
  124. i = 0
  125. for tr in table_tr_list: # 遍历每一个tr
  126. # 将每一个tr的数据根据td查询出来,返回结果为list对象
  127. if i == 0:
  128. title = 'MEETING PROBABILITIES'
  129. i = i + 1
  130. continue
  131. if i == 1:
  132. i = i + 1
  133. table_th_list = tr.find_elements(By.TAG_NAME, "th")
  134. row_list = []
  135. for th in table_th_list:
  136. row_list.append(th.text)
  137. if len(row_list) == 0:
  138. continue
  139. row_tuple = tuple(row_list)
  140. table_list.append(row_list)
  141. else:
  142. i = i + 1
  143. table_td_list = tr.find_elements(By.TAG_NAME, "td")
  144. row_list = []
  145. for td in table_td_list: # 遍历每一个td
  146. row_list.append(td.text) # 取出表格的数据,并放入行列表里
  147. if len(row_list) == 0:
  148. continue
  149. row_tuple = tuple(row_list)
  150. table_list.append(row_list)
  151. driver.quit()
  152. # list_text = content.strip().split('\n')
  153. # print(list_text)
  154. # ls = list()
  155. # title = ""
  156. # length = len(list_text)
  157. # for i in range(length):
  158. # line = list_text[i]
  159. # if i == 0:
  160. # title = line
  161. # continue
  162. # if i == 1:
  163. # line = line.replace('MEETING DATE', 'MEETING_DATE')
  164. # dataList = line.split(' ')
  165. # dataList[0] = 'MEETING DATE'
  166. # my_tuple = tuple(dataList)
  167. # ls.append(my_tuple) # 以元组的形式追加进空列表
  168. # continue
  169. # dataList = line.split(' ')
  170. # my_tuple = tuple(dataList)
  171. # ls.append(my_tuple) # 以元组的形式追加进空列表
  172. # 获取当前时间,并将其格式化为指定的形式
  173. current_time = datetime.datetime.now().strftime("%Y-%m-%d")
  174. # 构建新的文件路径
  175. book_name_xlsx = f'D:\pythonProject\metting\{current_time}.xlsx'
  176. # book_name_xlsx = f'/Users/xi/Desktop/{current_time}.xlsx'
  177. write_excel_xlsx(book_name_xlsx, title, table_list)
  178. url = 'http://47.102.213.75:8809/v1/test/resource/upload'
  179. file_path = book_name_xlsx # 替换为本地文件路径
  180. # file_path = '/Users/xi/Desktop/2023-10-15.xlsx' # 替换为本地文件路径
  181. print(file_path)
  182. print(datetime.datetime.now())
  183. response = send_file(url, file_path)
  184. print(response)