Python使用Selenium抓取百家乐HTML数据并转换为指定列表格式的方法
解决方案
1 调整元素定位逻辑,按桌拆分数据
你当前代码直接全局提取所有.svg--1nrnH元素,没有按游戏桌分组,会把多桌的结果混在一起,调整方案如下。你可以先通过浏览器F12元素检查工具找到游戏桌父容器对应的选择器,替换示例中的.table-container即可:
from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(executable_path='C:/chromedriver/chromedriver.exe') driver.get('https://ggl-maxim.com/') driver.find_element(By.XPATH, '//*[@id="body"]/div/div[2]/div/div[2]/fieldset/input[1]').send_keys('tnrud3080') driver.find_element(By.XPATH, '//*[@id="body"]/div/div[2]/div/div[2]/fieldset/input[2]').send_keys('tnrud3080') driver.find_element(By.XPATH, '//*[@id="body"]/div/div[2]/div/div[2]/fieldset/button[1]').click() time.sleep(2) driver.get('https://ggl-maxim.com/api/popup/popup_menu.asp?mobile=0&lobby=EVOLUTION') wait = WebDriverWait(driver, 20) wait.until(EC.frame_to_be_available_and_switch_to_it("gameIframe")) wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".svg--1nrnH"))) # 定位所有游戏桌容器,替换为实际的选择器 table_containers = driver.find_elements(By.CSS_SELECTOR, ".table-container") all_table_result = [] for table in table_containers: # 提取当前桌的所有结果标识 color_dots = table.find_elements(By.CSS_SELECTOR, ".svg--1nrnH") single_table_res = [] for dot in color_dots: # 从svg填充色判断对应结果,比读取innerHTML更稳定 fill = dot.value_of_css_property('fill').lower() if 'red' in fill or '#ff0000' in fill: single_table_res.append('red') elif 'blue' in fill or '#0000ff' in fill: single_table_res.append('blue') # 若有和局,补充绿色对应的判断即可 # 如果你需要调整结果顺序,比如倒序,加[::-1]即可:single_table_res = single_table_res[::-1] all_table_result.append(single_table_res) # 输出所有桌的结果 for table_id, res in enumerate(all_table_result, 1): print(f"{table_id}号桌结果:{res}")
2 已有单桌字符串的转换方法
如果你已经拿到了空格分隔的单桌结果字符串,直接调用split方法即可转成你需要的列表格式:
raw_result = "red blue red blue red blue red" result_list = raw_result.split() print(result_list)
如果需要调整结果的排列顺序,直接对列表做倒序或自定义排序即可。
内容的提问来源于stack exchange,提问作者Kate shim
相关产品推荐
相关产品推荐

