Home > Software engineering >  How to get text of all elements of a webpage that are blue in color in selenium in python
How to get text of all elements of a webpage that are blue in color in selenium in python

Time:01-27

I want to have text of all the elements that are blue in color from a webpage using selenium in python.

However I am unable to find the right xpath for the corresponding property. Below is my code, can somebody please let me know what mistake I am making here:-

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import gdown

service = webdriver.chrome.service.Service('./chromedriver')
service.start()
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options = options.to_capabilities()
driver = webdriver.Remote(service.service_url, options)
links = ["https://www.insightsonindia.com/2023/01/26/mission-2023-secure-daily-upsc-mains-answer-writing-practice-26-january-2023/"]
for link in links:
    print(link)
    driver.get(link)
    elems = driver.find_elements_by_xpath("//strong[style*='color:#0000ff']")
    for elem in elems:
        print(elem.text)

CodePudding user response:

The color is an attribute of the span not of the strong so XPATH should look like:

//span[contains(@style,'color: #0000ff')]

or use * to be not that specific and look for all:

//*[contains(@style,'color: #0000ff')]

In newer version of selenium avoid use of find_element_by_* because this are deprecated in the latest version:

from selenium.webdriver.common.by import By
...
driver.find_elements(By.XPATH, "//span[contains(@style,'color: #0000ff')]")

CodePudding user response:

Your xpath request is missing a space. He should be like that:

//span[@style='color: #0000ff;']

  • Related