metting.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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, NoSuchElementException, ElementNotInteractableException
  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. try:
  101. btn_pop = get_element(driver, '/html/body/div[4]/div[3]/div/section/span')
  102. if btn_pop:
  103. btn_pop.click()
  104. accept_btn = get_element(driver, '//*[@id="onetrust-accept-btn-handler"]')
  105. if accept_btn:
  106. accept_btn.click()
  107. except ElementNotInteractableException:
  108. # 如果元素不存在,则隐藏报错并执行其他操作
  109. print("元素不可点击")
  110. ''
  111. WebDriverWait(driver, 10).until(
  112. EC.visibility_of_element_located((By.XPATH, '/html/body/main/div/div[4]/div/iframe'))) # iframe是否出现
  113. # page_height = driver.execute_script('return document.documentElement.scrollHeight') # 页面高度
  114. driver.execute_script("window.scrollBy(0,{})".format(600))
  115. driver.switch_to.frame("cmeIframe-jtxelq2f")
  116. sleep(2)
  117. # button = driver.find_element(By.XPATH, '//*[@id="ctl00_MainContent_ucViewControl_IntegratedFedWatchTool_lbPTree"]')
  118. driver.execute_script(
  119. "javascript:__doPostBack('ctl00$MainContent$ucViewControl_IntegratedFedWatchTool$lbPTree','')")
  120. WebDriverWait(driver, 10).until(
  121. EC.visibility_of_element_located((By.XPATH, '//*[@id="MainContent_pnlContainer"]/div[3]/div/div/div[1]/table')))
  122. table = driver.find_element(By.XPATH, '//*[@id="MainContent_pnlContainer"]/div[3]/div/div/div[1]/table')
  123. table.screenshot(r'meeting.png')
  124. print(table.text)
  125. # 按行查询表格的数据,取出的数据是一整行,按空格分隔每一列的数据
  126. table_tr_list = table.find_elements(By.TAG_NAME, "tr")
  127. table_list = [] # 存放table数据
  128. th_flag = False
  129. title = 'MEETING PROBABILITIES'
  130. i = 0
  131. for tr in table_tr_list: # 遍历每一个tr
  132. # 将每一个tr的数据根据td查询出来,返回结果为list对象
  133. if i == 0:
  134. title = 'MEETING PROBABILITIES'
  135. i = i + 1
  136. continue
  137. if i == 1:
  138. i = i + 1
  139. table_th_list = tr.find_elements(By.TAG_NAME, "th")
  140. row_list = []
  141. for th in table_th_list:
  142. row_list.append(th.text)
  143. if len(row_list) == 0:
  144. continue
  145. row_tuple = tuple(row_list)
  146. table_list.append(row_list)
  147. else:
  148. i = i + 1
  149. table_td_list = tr.find_elements(By.TAG_NAME, "td")
  150. row_list = []
  151. for td in table_td_list: # 遍历每一个td
  152. row_list.append(td.text) # 取出表格的数据,并放入行列表里
  153. if len(row_list) == 0:
  154. continue
  155. row_tuple = tuple(row_list)
  156. table_list.append(row_list)
  157. driver.quit()
  158. # list_text = content.strip().split('\n')
  159. # print(list_text)
  160. # ls = list()
  161. # title = ""
  162. # length = len(list_text)
  163. # for i in range(length):
  164. # line = list_text[i]
  165. # if i == 0:
  166. # title = line
  167. # continue
  168. # if i == 1:
  169. # line = line.replace('MEETING DATE', 'MEETING_DATE')
  170. # dataList = line.split(' ')
  171. # dataList[0] = 'MEETING DATE'
  172. # my_tuple = tuple(dataList)
  173. # ls.append(my_tuple) # 以元组的形式追加进空列表
  174. # continue
  175. # dataList = line.split(' ')
  176. # my_tuple = tuple(dataList)
  177. # ls.append(my_tuple) # 以元组的形式追加进空列表
  178. # 获取当前时间,并将其格式化为指定的形式
  179. current_time = datetime.datetime.now().strftime("%Y-%m-%d")
  180. # 构建新的文件路径
  181. book_name_xlsx = f'D:\pythonProject\metting\{current_time}.xlsx'
  182. # book_name_xlsx = f'/Users/xi/Desktop/{current_time}.xlsx'
  183. write_excel_xlsx(book_name_xlsx, title, table_list)
  184. url = 'http://47.102.213.75:8809/v1/test/resource/upload'
  185. file_path = book_name_xlsx # 替换为本地文件路径
  186. # file_path = '/Users/xi/Desktop/2023-10-15.xlsx' # 替换为本地文件路径
  187. print(file_path)
  188. print(datetime.datetime.now())
  189. response = send_file(url, file_path)
  190. print(response)