python - selenium find_element_by_css_selector 用于长类名

标签 python selenium selenium-chromedriver

我已经多次尝试使用教程中的其他指令代码和空格,效果很好。但是,当我刚刚更改 URL 和以下类时,它会给出错误:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=100.0.4896.88)

当我使用教程代码时一切正常。

这是我的代码(我已经从互联网上解决了一些 chrome 驱动程序问题)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(options=options)

driver.get("https://raritysniper.com/nft-drops-calendar")

time.sleep(1)

link = driver.find_element_by_css_selector(".w-full.h-full.align-middle.object-cover.dark:brightness-80.dark:contrast-103.svelte-f3nlpp").get_attribute("alt")

print(link)

我正在尝试获取每个项目的属性并将它们放入 csv 中。 (请引用截图)

Screen shot of HTML that I am trying to extract

如果有人能描述我在代码中遇到的问题,那就太好了。

谢谢!

最佳答案

您正在使用的 CSS_SELECTOR

.w-full.h-full.align-middle.object-cover.dark:brightness-80.dark:contrast-103.svelte-f3nlpp

并不真正匹配 HTML 中的任何元素。

相反,您应该使用此 CSS_SELECTOR:

div.w-full.h-full.align-middle img:not(.placeholder)

在代码中:

driver.maximize_window()

wait = WebDriverWait(driver, 30)

driver.get("https://raritysniper.com/nft-drops-calendar")

#time.sleep(1)

first_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.w-full.h-full.align-middle img:not(.placeholder)")))
print(first_element.get_attribute('alt'))
print(first_element.get_attribute('src'))

导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

输出:

NEON PLEXUS
https://media.raritysniper.com/featured/neon-plexus_1648840196045_3.webp

Process finished with exit code 0

关于python - selenium find_element_by_css_selector 用于长类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71883434/

相关文章:

python - 从 Selenium IDE 到 Python - 没有这样的元素

python - Selenium 意外出现问题

python - 从 numpy 数组中获取最大或最小 n 个元素? (最好不要压平)

python - 如何使用 Selenium 从搜索结果中提取 Google 链接的 href?

javascript - Selenium 不执行 javascript

google-chrome-extension - Selenium WebDriverJS - 测试 Chrome 扩展安装

python - 确定近似相机矩阵

python - 正则表达式更改搜索字符串中的位置

python - 如何使用python将字典转换为字典列表

java - 是否可以从被调用的方法中写入 testng 测试的名称?