【问题标题】:How to get text of all elements of a webpage that are blue in color in selenium in python如何在python中的selenium中获取网页中所有蓝色元素的文本
【发布时间】:2023-01-31 02:52:42
【问题描述】:

我想在 python 中使用 selenium 从网页中获取所有蓝色元素的文本。

但是我无法为相应的属性找到正确的 xpath。 下面是我的代码,有人可以让我知道我在这里犯了什么错误:-

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)

【问题讨论】:

    标签: python-3.x selenium web-scraping xpath


    【解决方案1】:

    颜色是 span 的属性,而不是 strong 的属性,因此 XPATH 应该如下所示:

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

    或使用 * 不那么具体并查找所有内容:

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

    在较新版本的 selenium 中避免使用 find_element_by_* 因为这在最新版本中已被弃用:

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

    【讨论】:

      【解决方案2】:

      您的 xpath 请求缺少一个空格。他应该是这样的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2020-12-11
        • 2018-12-11
        相关资源
        最近更新 更多