TimeOut Exception Not Working, Element Not Interactable Selenium - selenium

In this section of my text, I am looping to select all check boxes across a number of pages (successful). When the next button is no longer enabled (and thus no more pages to turn, try command), I want to click the apply button. There are two different apply buttons, a visible and invisible one. The way my text is written, I receive an element not interactable exception, and thus my timeout exception isn't seen through. That's unexpected because the button I am trying to click is clearly visible and clickable (manually).
Original website: https://icem.data-archive.ac.uk/#step2
Does anyone have an idea what could be causing this element not interactable? I have attached a photo of the HTML of the two applied buttons: https://i.stack.imgur.com/xBl9X.png
Note: introducing WebDriverWait on the exception command just induces another timeoutexception.
county_pop < 1000000:
while True:
checklist = webD.find_elements_by_xpath('//*[#class="modal-content"]//input[#class="ng-pristine ng-valid"]')
for elem in checklist:
elem.click()
try:
WebDriverWait(webD, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[not(contains(#class, "disabled"))]/a[.="Next"]'))).click()
except TimeoutException:
webD.find_element_by_xpath('//div[#class="modal-content"]//div[#class="col-sm-3 text-left visible-xs"]/button').click()
Script until then:
import selenium
import time
from selenium import webdriver as wd
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException, NoSuchWindowException
from selenium.webdriver.common.action_chains import ActionChains
chrome_path = r'C:\webdrivers\chromedriver.exe'
webD=wd.Chrome(executable_path=chrome_path)
webD.get('https://beta.ukdataservice.ac.uk/myaccount')
WebDriverWait(webD, 20).until(EC.element_to_be_clickable(
(By.XPATH, '//*[#id="myaccount-login"]/div/div/div/div/div/div[2]/div/div/div/form/div/p/button'))).click()
WebDriverWait(webD, 20).until(EC.element_to_be_clickable(
(By.XPATH, '//*[#id="username"]'))).send_keys('ukd1217078879')
WebDriverWait(webD, 20).until(EC.element_to_be_clickable(
(By.XPATH, '//*[#id="password"]'))).send_keys('Census4Me!')
webD.find_element_by_xpath('/html/body/div/div/div[2]/div[1]/form/div[6]/button').click()
webD.get('https://icem.data-archive.ac.uk/#step1')
#YEARS LOOP BEGINS
for year in [1851, 1861, 1881, 1891, 1901, 1911]:
webD.find_element_by_xpath("//b[#class='ng-binding' and text()='{}']/preceding-sibling::input[#type='radio']".format(str(year))).click()
# Continuing to England & Step 2, Opening Counties Variable, More Variables
WebDriverWait(webD, 20).until(EC.element_to_be_clickable((By.XPATH, '//b[#id = "country_england"]/preceding-sibling::input'))).click()
webD.find_element_by_xpath('//html/body/div/section/section[1]/article[2]/div/div/button').click()
WebDriverWait(webD, 20).until(EC.element_to_be_clickable(
(By.XPATH, '//*[#id="county_category"]/button[1]'))).click()
WebDriverWait(webD, 20).until(EC.element_to_be_clickable(
(By.XPATH, '//*[#id="county_category"]/div[2]/div/div[2]/button'))).click()
# COUNTIES LOOP BEGINS
conto = 1
count = conto
while count > 10: #Getting to the correct county page
webD_find_element_by_link_text('Next').click()
count = count - 10
for i in range(count,11):
#Clicking correct county
WebDriverWait(webD, 20).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[3]/div/div/div[3]/div[{}]/label/input'.format(count)))).click()
#Adding 1 to absolute count, conto
conto = conto + 1
#Store variables
county_text = webD.find_element_by_xpath('/html/body/div[3]/div/div/div[3]/div[{}]/label'.format(count)).text
county_pop = int(county_text.split("(")[-1].replace(")","").replace(",", ""))
print(county_pop)
#Apply County Selection, open HISCO & More Variables
WebDriverWait(webD, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Apply')]"))).click()
WebDriverWait(webD, 20).until(EC.presence_of_element_located((By.XPATH, '//span[#class = "ice-allow-download-alert ng-animate ng-hide-remove ng-hide-remove-active"]')))
WebDriverWait(webD, 20).until(EC.invisibility_of_element_located((By.XPATH, '//span[#class = "ice-allow-download-alert ng-animate ng-hide-remove ng-hide-remove-active"]')))
WebDriverWait(webD, 20).until(EC.presence_of_element_located((By.XPATH, '//b[text()[contains(.,"HISCO classified occupation")]]/..'))).click()
WebDriverWait(webD, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="workhistoryunit_category"]/div[2]/div/div[2]/button'))).click()
#HISCO OCCUPATION SELECTION LOOP
if county_pop < 1000000:
while True:
checklist = webD.find_elements_by_xpath('//*[#class="modal-content"]//input[#class="ng-pristine ng-valid"]')
for elem in checklist:
elem.click()
try:
WebDriverWait(webD, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[not(contains(#class, "disabled"))]/a[.="Next"]'))).click()
except TimeoutException:
webD.find_element_by_xpath('//div[#class="modal-content"]//div[#class="col-sm-3 text-left visible-xs"]/button').click()

temp = True
if county_pop < 1000000:
while temp:
checklist = webD.find_elements_by_xpath(
'//*[#class="modal-content"]//input[#class="ng-pristine ng-valid"]')
for elem in checklist:
elem.click()
try:
WebDriverWait(webD, 10).until(EC.element_to_be_clickable(
(By.XPATH, '//*[not(contains(#class, "disabled"))]/a[.="Next"]'))).click()
except:
WebDriverWait(webD, 10).until(EC.element_to_be_clickable(
(By.XPATH, '//button[contains(text(),"Apply")]'))).click()
temp = False
in while loop you had True which will make it run infinitly , change it to a varaible Temp and set it to false as soon as the next button is not clickable.
Also use webdriver wait and click on the first button

Related

Unable to extract values linked to data points from an interactive line chart

I am trying to extract the percentage values (Target Rate Probability) from an interactive chart with preselected conditions "13 Dez23" and "Historical" on the following website: https://www.cmegroup.com/markets/interest-rates/cme-fedwatch-tool.html?redirect=/trading/interest-rates/countdown-to-fomc.html. The percentage probabilities only appear when I hover over the respective data points with a mouse.
I have tried the following:
XPath of tried element: /html/body/form/div[3]/div[2]/div[3]/div[1]/div/div/div[1]/div/div[3]/div[3]/div/div/div/div[1]/div/svg/g[5]/g[2]/path[2]
1. Method Approach: Webdriverwait in order for the elements to load on the page
1. Method Error: TimeoutException
2. Method Approach:
driver.execute_script("document.evaluate('/html/body
/form/div[3]/div[2]/div[3]/div[1]/div/div/div[1]/div/div[3]/div[3]/div/div/div/div[1]/div/svg/g[5]/g[2]/path[2]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style.display = 'block';")
2. Method Error:
selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read properties of null (reading 'style')
3. Method Approach:
driver.execute_script("document.evaluate('/html/body/form
/div[3]/div[2]/div[3]/div[1]/div/div/div[1]/div/div[3]/div[3]/div/div/div/div[1]/div/svg/g[5]/g[2]/path[2]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style.visibility = 'visible';")
3. Method Error:
selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read properties of null (reading 'style')
EC: Invisibility of element is True
**Code: **
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import datetime as dt
import time
driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())
driver.get('https://www.cmegroup.com/markets/interest-rates/cme-fedwatch-tool.html?redirect=/trading/interest-rates/countdown-to-fomc.html')
time.sleep(10)
page_source=driver.page_source
time.sleep(5)
driver.switch_to.frame('cmeIframe-jtxelq2f')
time.sleep(5)
driver.find_element(By.XPATH,"/html/body/form/div[3]/div[2]/div[3]/div[1]/div/div/div[1]/div/div[3]/div[3]/div/div/ul/li[8]/a").click()
time.sleep(5)
driver.find_element(By.CSS_SELECTOR,"#ctl00_MainContent_ucViewControl_IntegratedFedWatchTool_lbHistorical").click()
time.sleep(10)
# 175-200 target rate probability
action = webdriver.ActionChains(driver)
CSS_Selector = '#highcharts-986wlrn-17 > svg > g.highcharts-series-group > g.highcharts-markers.highcharts-series-0.highcharts-line-series.highcharts-color-0.highcharts-tracker > path.highcharts-halo.highcharts-color-0'
# Wait for the element
wait = WebDriverWait(driver, 10)
# Check, if the element is invisible (IT IS)
print(wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, CSS_Selector))))
#Change the data-z-index', '4' to put infront of the other elements (DOESNT WORK!)
driver.execute_script("document.querySelector('#highcharts-986wlrn-17 > svg > g.highcharts-series-group > g.highcharts-markers.highcharts-series-0.highcharts-line-series.highcharts-color-0.highcharts-tracker > path.highcharts-halo.highcharts-color-0').setAttribute('data-z-index', '4')")
time.sleep(10)
#Doesnt find the first element of 175-200 (DOESNT WORK!)
element = driver.find_element(By.CSS_SELECTOR,'#highcharts-986wlrn-17 > svg > g.highcharts-series-group > g.highcharts-markers.highcharts-series-0.highcharts-line-series.highcharts-color-0.highcharts-tracker > path.highcharts-halo.highcharts-color-0')
# Move the mouse over the very left element first element 175-200 (DOESNT WORK!)
action.move_to_element(element)
action.perform()
#Determining the location and size in order for the mouse to move along the interactive chart for 175-200
loc = element.location
size = element.size
#moving to right end of the interactive chart for 175-200 (DOESNT WORK!)
action.move_to_element_with_offset(element,510, 0).perform() #found 510 when inspecting the chart metrics
#first date (found on the very left of the chart) (DOESNT WORK!)
driver.find_element(By.XPATH,'/html/body/form/div[3]/div[2]/div[3]/div[1]/div/div/div[1]/div/div[3]/div[3]/div/div/div/div[1]/div/svg/g[10]/g/text/tspan[1]')
#first value (found on the very left of the chart) (DOESNT WORK!)
driver.find_element(By.XPATH,'/html/body/form/div[3]/div[2]/div[3]/div[1]/div/div/div[1]/div/div[3]/div[3]/div/div/div/div[1]/div/svg/g[5]/g[2]/path[1]')
#setting the limit of when to break out of the while loop (DOESNT WORK!)
limit = dt.datetime.strptime('Thu, May 5, 2022', '%a, %B %-m, %B')
pace = -5
dictionary = {}
while True:
#moving back to the very left first element of the interactive chart
action.move_by_offset(pace, 0).perform() # moving by a pace of -5 (-5 is trial value)
date = driver.find_element(By.CSS_SELECTOR,'#highcharts-986wlrn-17 > svg > g.highcharts-tooltip > g.highcharts-label.highcharts-tooltip-header.highcharts-tooltip-box > text').text
value = driver.find_element(By.CSS_SELECTOR,'#highcharts-986wlrn-17 > svg > g.highcharts-tooltip > g.highcharts-label.highcharts-tooltip-box.highcharts-color-0 > text').text
if dt.datetime.strptime(date, '%a, %B %-m, %B') < limit:
break
# add results to dictionary
if date in dictionary:
pass
else:
dictionary[date] = value
driver.quit()
[![Interactive Line Chart][1]][1]
[1]: https://i.stack.imgur.com/ZDHQt.jpg
The code below assumes that you already clicked on "13 Dec23" and "Historical":
import time
import pyautogui # pip install pyautogui
# sleep 3 seconds so that you can switch to the browser and move the mouse to the start position
time.sleep(3)
# start position: put mouse on chart's left border, for example between 0% and 20%
start_pos = pyautogui.position()
# this works only if the tooltip containing the percentage values was already been displayed once
old_values = driver.find_element(By.CSS_SELECTOR, 'g.highcharts-tooltip').text.replace('\n','').split('●')
data = []
for k in range(500):
pyautogui.moveTo(start_pos.x + 3*k , start_pos.y)
new_values = driver.find_element(By.CSS_SELECTOR, 'g.highcharts-tooltip').text.replace('\n','').split('●')
if new_values != old_values:
old_values = new_values
data.append(new_values)
# uncomment this if you want the mouse to move slower
# time.sleep(.1)
data will then be a list of lists, where each list contains the day label and the corresponding percentage values (as strings)
[['Thu, May 5, 2022',
'350-375: 17.18%',
'325-350: 28.11%',
'300-325: 27.01%',
'250-275: 4.39%',
'275-300: 14.80%',
'225-250: 0.65%',
'375-400: 6.27%',
'400-425: 1.36%',
'425-450: 0.17%'],
['Fri, May 6, 2022',
'350-375: 15.54%',
'325-350: 26.14%',
'300-325: 26.94%',
'250-275: 6.08%',
'275-300: 16.73%',
'225-250: 1.24%',
'375-400: 5.71%',
'400-425: 1.29%',
'425-450: 0.17%',
'200-225: 0.14%'],
... etc ...

Trying to fetch option chain data from NSE... but getting error using Chromedriver

Below is the code through which I am trying to fetch option chain data but I am getting errors.
Any help will be appreciated.
Thanks
Also, if someone can help me with a better code to record tick data, that would be great
import time
import datetime
import pandas as pd
from bs4 import BeautifulSoup,SoupStrainer
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# from selenium.webdriver import Chrome as uc
# options=chrome_options
df=pd.DataFrame(columns=['SNO','call OI','call CHNG IN OI','call VOLUME','call IV','call LTP','call CHNG','call BID QTY','call BID PRICE','call ASK PRICE','call ASK QTY','STRIKE PRICE','put BID QTY','put BID PRICE','put ASK PRICE','put ASK QTY','put CHNG','put LTP','put IV','put VOLUME','put CHNG IN OI','put OI'])
chrome_options = Options()
chrome_options.add_argument("--log-level=3")
from selenium.webdriver import Chrome as uc
chrome_options = uc.ChromeOptions() #new solution
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(executable_path=r"C:\Users\rohit taparia\Downloads\chromedriver_win32\chromedriver.exe",options=chrome_options)
driver.get('https://www.nseindia.com/get-quotes/derivatives?symbol=BANKNIFTY')
driver.minimize_window()
time.sleep(3)
for j in range(0,50):
print(j)
#.....refresh the page and read data again
driver.refresh()
continue_link1 = driver.find_element_by_xpath('''//*[#id="subtab-derivatives"]/div[2]/nav/div/div/a[2]''')
time.sleep(10)
filter_tag=SoupStrainer("table")
continue_link1.click()
time.sleep(3)
rtime = str(driver.find_element_by_xpath('''//*[#id="asondate"]''').text)
if rtime=='':
continue
print(rtime)
page=driver.page_source
soup = BeautifulSoup(page, "html.parser",parse_only=filter_tag)
gdp_table = soup.find("table", attrs={"id": "optionChainTable-indices"})
gdp_table_data = gdp_table.tbody.find_all("tr")
if len(gdp_table_data)==1:
continue
else:
for i in range (0,len(gdp_table_data)):
list1 = []
for td in gdp_table_data[i].find_all("td"):
# remove any newlines and extra spaces from left and right
cell_text=td.text
if cell_text is None or cell_text=='':
cell_text ='0'
cell_text=cell_text.replace(',','')
list1.append(cell_text)
if len(list1) > 0:
list1 = ['0' if i=='-' else i for i in list1]
else:
continue
del list1[0]
del list1[-1]
list1 = list(map(float, list1))
list1.insert(0,rtime)
df.loc[len(df)] = list1
df.to_excel("option-data.xlsx")

Selenium StaleElementReferenceException and command(related wait) does not work

When I run below Program, Code "option2[opt2].click()" work well.
But second "option2[opt2].click()" occur "StaleElementReferenceException"
I tried to solve this problem with "time.sleep(), implicitly_wait(), WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, {Xpath}).
But Doesn't work.
What is the problem........
#If you run my program, you can understand my code easily. I am Beginer in Programming and Korean. If explanation is not enough... sorry :( Please help me........
from selenium import webdriver
import pandas as pd
import time
import random
options = webdriver.ChromeOptions()
options.add_argument("user-agent={myagent}")
browser = webdriver.Chrome(options = options)
browser.get("https://yeyak.seoul.go.kr/web/main.do") #첫페이지로
browser.maximize_window()
#노원구 공간시설, 문화체험, 교육강좌 카테고리 크롤링
#column 이름
all_column_name = ['구', '카테고리', '대상', '장소', '이용기간', '접수기간', '선별방법',
'모집정원', '신청제한', '취소기간', '이용요금', '예약방법', '문의전화']
all_data = []
#노원구 선택(이미 Click되어있는데, 또 Click을 하면 오류가 남)
browser.find_element_by_xpath("//*[#id=\"sch_loc\"]/option[11]").click()
time.sleep(1)
for i in range(2,5):
#공간시설, 문화체험, 교육강좌 카테고리 선택
browser.find_element_by_xpath(f"//*[#id='contents']/div[1]/div[1]/div/div/div[1]/ul/li[{i}]").click()
time.sleep(1)
category_name = browser.find_element_by_xpath(f"//*[#id='contents']/div[1]/div[1]/div/div/div[1]/ul/li[{i}]").text
district = browser.find_element_by_xpath("//*[#id=\"contents\"]/div[1]/div[1]/div/div/div[2]/div[3]/div[1]/select/option[11]").text #구 이름 district 저장
#시설 선택 버튼_소주제
button2 = browser.find_element_by_xpath("//*[#id=\"contents\"]/div[1]/div[1]/div/div/div[2]/div[3]/div[2]/select")
button2.find_elements_by_tag_name("option")
option2 = button2.find_elements_by_tag_name("option")
if len(option2) == 1: #만약 옵션이 별도로 없는 경우 다음 카테고리로 넘어가기
continue
for opt2 in range(1, len(option2)+1):
print(option2[opt2].text)
option2[opt2].click()
time.sleep(1)
#시설 상세 선택 버튼
button3 = browser.find_element_by_xpath("//*[#id=\"contents\"]/div[1]/div[1]/div/div/div[2]/div[3]/div[3]/select")
option3 = button3.find_elements_by_tag_name("option")
if len(option3) == 1: #만약 옵션이 별도로 없는 경우 다음 카테고리로 넘어가기
continue
for opt3 in range(1, len(option3)+1):
small_data = []
option3[opt3].click()
time.sleep(1)
#예약하기 버튼 클릭
browser.find_element_by_xpath("//*[#id=\"contents\"]/div[1]/div[1]/div/div/div[2]/div[3]/button").click()
time.sleep(1)
#테이블에서 데이터 가져오기
table = browser.find_element_by_xpath("//*[#id=\"aform\"]/div[1]/div[2]/ul")
rows = table.find_elements_by_tag_name("li")
small_data.append(district) # 구 이름 넣기
small_data.append(category_name) # 카테고리 이름 넣기
for row in rows:
small_data.append(row.text.split("\n")[1])
all_data.append(small_data)
time.sleep(random.uniform(2,3))
browser.get("https://yeyak.seoul.go.kr/web/main.do")
time.sleep(random.uniform(2,3))
browser.find_element_by_xpath("//*[#id=\"sch_loc\"]/option[11]").click() #노원구 클릭
time.sleep(random.uniform(2,3))
browser.find_element_by_xpath(f"//*[#id='contents']/div[1]/div[1]/div/div/div[1]/ul/li[{i}]").click() #카테고리 클릭
time.sleep(random.uniform(2,3))
browser.find_element_by_xpath(f"//*[#id=\"contents\"]/div[1]/div[1]/div/div/div[2]/div[3]/div[2]/select/option[{opt2}]")
time.sleep(random.uniform(2,3))
if opt3 == len(option3)+1:
break

X-Path - How To Pull This Field?

My code goes into a webpage, clicks on a record, which then drops other records.
Is there a way to use xPath to pull all of these drop-down titles?
Currently, I copied the first drop down titles full xpath, and its only pulling the first one.
That is fine, but how do I pull all entry titles that drop down?
My current code is specifically only for the first line
from selenium import webdriver
import time
driver = webdriver.Chrome()
for x in range (1,2):
driver.get(f'https://library.iaslc.org/conference-program?product_id=24&author=&category=&date=&session_type=&session=&presentation=&keyword=&available=&cme=&page={x}')
time.sleep(4)
productlist_length = len(driver.find_elements_by_xpath("//div[#class='accordin_title']"))
for i in range(1, productlist_length + 1):
product = driver.find_element_by_xpath("(//div[#class='accordin_title'])[" + str(i) + "]")
title = product.find_element_by_xpath('.//h4').text.strip()
buttonToClick = product.find_element_by_xpath('.//div[#class="sign"]')
buttonToClick.click()
time.sleep(5)
dropDownTitle=product.find_element_by_xpath('//*[#id="accordin"]/div/ul/li[1]/div[2]/div/ul/li/div[1]/div[3]/h4').text #this line is the full xpath
print(dropDownTitle)
So can you check with the below line of code
#try to execute it in maximize mode sometimes element is overlayed
driver.maximize_window()
for x in range (1,5):
driver.get(f'https://library.iaslc.org/conference-program?product_id=24&author=&category=&date=&session_type=&session=&presentation=&keyword=&available=&cme=&page={x}')
time.sleep(4)
productlist_length = len(driver.find_elements_by_xpath("//div[#class='accordin_title']"))
for i in range(1, productlist_length + 1):
product = driver.find_element_by_xpath("(//div[#class='accordin_title'])[" + str(i) + "]")
title = product.find_element_by_xpath('.//h4').text.strip()
#So at some point the dropdown doesn't display any records so at that point it throws ClickInterceptedException, Also I ActionChain to move to the particular element
buttonToClick = product.find_element_by_xpath('.//*[#class="info_right"]/h4')
action = ActionChains(driver)
action.move_to_element(buttonToClick).click().perform()
time.sleep(5)
#Here if you just provide the index of the li it will print the title
dropDownTitle=product.find_element_by_xpath("//*[#id='accordin']/div/ul/li["+str(i)+"]/div[1]/div[3]/h4").text
print(dropDownTitle)
import
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
Output

Not scraping xpath correctly

I'm trying to use the following xpath for this page but it is not loading correctly.
groups = ".//*[contains(#class, 'sl-CouponParticipantWithBookCloses_Name ')]"
xp_bp1 = ".//following::div[contains(#class,'sl-MarketCouponValuesExplicit33')][./div[contains(#class,'gl-MarketColumnHeader')][.='1']]//span[#class='gl-ParticipantOddsOnly_Odds']"
The output currently is..
[['3.00'], ['3.00'], ['3.00'] etc,,
Desired:
[['3.00'], ['1.30'], ['1.25'] etc,,
Data I am after
Script:
import csv
import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
driver = webdriver.Chrome()
driver.set_window_size(1024, 600)
driver.maximize_window()
driver.get('https://www.bet365.com.au/#/AC/B1/C1/D13/E108/F16/S1/')
driver.get('https://www.bet365.com.au/#/AC/B1/C1/D13/E108/F16/S1/')
time.sleep(10)
groups = ".//*[contains(#class, 'sl-CouponParticipantWithBookCloses_Name ')]"
#//div[contains(#class, 'gl-ParticipantOddsOnlyDarker gl-ParticipantOddsOnly gl-Participant_General sl-MarketCouponAdvancedBase_LastChild ')]
xp_bp1 = ".//following::div[contains(#class,'sl-MarketCouponValuesExplicit33')][./div[contains(#class,'gl-MarketColumnHeader')][.='1']]//span[#class='gl-ParticipantOddsOnly_Odds']"
while True:
try:
time.sleep(2)
data = []
for elem in driver.find_elements_by_xpath(groups):
try:
bp1 = elem.find_element_by_xpath(xp_bp1).text
except:
bp1 = None
url1 = driver.current_url
data.append([bp1])
print(data)
url1 = driver.current_url
with open('test.csv', 'a', newline='', encoding="utf-8") as outfile:
writer = csv.writer(outfile)
for row in data:
writer.writerow(row + [url1])
except TimeoutException as ex:
pass
except NoSuchElementException as ex:
print(ex)
break