I am trying to print the line of a set of webpages using selenium.
Here is my piece of code so far.
import selenium
from selenium import webdriver as wb
webD=wb.Chrome("C:\Program Files (x86)\chromedriver.exe")
webD.get('https://www.flashscore.com/')
webD.maximize_window() # For maximizing window
webD.implicitly_wait(2) # gives an implicit wait for 20 seconds
webD.find_element_by_id('onetrust-reject-all-handler').click()
matchpages = webD.find_elements_by_class_name('preview-ico.icon--preview')
for matchpages in matchpages:
matchpages.click()
Now, I want to show the full piece of text on the webpage by doing:
driver.find_element(By.CLASS_NAME,"smallArrow-ico").click()
This should be done for every webpage in the for loop.
In addition to this i want to print out the following line:
main = driver.find_element(By.XPATH,"//div[@class='previewLine' and ./b[text()='Hot
stat:']]").text
main = main.replace('Hot stat:','')
print(main)
How can I include both pieces of text in the for loop?
Thanks in advance.
CodePudding user response:
The element you are trying to click is a bit tricky.
Try this:
matchpages = webD.find_elements_by_xpath("//*[@class='preview-ico icon--preview']//*[name()='use']")
for matchpages in matchpages:
matchpages.click()
By clicking the element above a new window opens. So you have to switch to the new window handle in order to access elements there, to close it when you finished and to switch to the main window to continue working there.
So you code can be something like this:
wait = WebDriverWait(driver, 20)
matchpages = webD.find_elements_by_xpath("//*[@class='preview-ico icon--preview']//*[name()='use']")
for matchpages in matchpages:
matchpages.click()
new_window = driver.window_handles[1]
original_window = driver.window_handles[0]
driver.switch_to_window(new_window)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.previewShowMore.showMore"))).click()
main = driver.find_element(By.XPATH,"//div[@class='previewLine' and ./b[text()='Hot stat:']]").text
main = main.replace('Hot stat:','')
print(main)
driver.close()
driver.switch_to_window(original_window)
To use the web driver wait you will need the following imports:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC