提问人:childshoals 提问时间:11/6/2023 最后编辑:childshoals 更新时间:11/7/2023 访问量:62
用 Selenium 抓取 div
Scraping div with Selenium
问:
我正在尝试选择一个元素以在页面上单击它 (https://twitchtracker.com/riotgames/games)。该元素是日历弹出窗口中的可选日期。
是的
<div class="day unit in-range" data-time="1698822000000">1</div>
.
有没有办法使用元素选择元素。data-time="1698822000000"
我尝试使用By.CSS_SELECTOR,但我总是收到“无法找到元素”错误。
答:
0赞
Mouad Slimane
11/6/2023
#1
您可以使用该函数从 Selenium Web 元素中获取值,如下所示:get_attribute
tag
element= driver.find_element(By.XPATH,"//div[@class='day unit in-range']")
date_time=element.get_attribute('date_time')
评论
0赞
childshoals
11/6/2023
感谢您的回复!不幸的是,运行第一行给了我selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”:“//div[@class='天单位在范围内']”}
0赞
Firas Kaabi
11/6/2023
#2
element = driver.find_element(By.CSS_SELECTOR, "div.day.unit.in-range")
date_time = element.get_attribute('data-time')
评论
0赞
childshoals
11/7/2023
感谢您的回复!不幸的是,我也收到了这个错误:(selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“css selector”,“selector”:“div.day.unit.in-range”}
1赞
Yaroslavm
11/7/2023
#3
你的元素被放置在shadow-root中,所以要得到它,你需要找到它的主机,并通过获取属性进入它。shadowRoot
然后,只要您的元素不可交互,您就需要模拟 js click。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
def get_shadow_root(element):
return driver.execute_script('return arguments[0].shadowRoot', element)
def click_js(element):
return driver.execute_script('return arguments[0].click()', element)
url = ('https://twitchtracker.com/riotgames/games')
driver.get(url)
driver.maximize_window()
wait = WebDriverWait(driver, 20)
host = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'easepick-wrapper')))
date_element = get_shadow_root(host).find_element(By.CSS_SELECTOR, 'div.unit.in-range')
click_js(date_element)
0赞
bhdzllr
11/7/2023
#4
我查看了您的网站,日历天数在影子根中。请先尝试选择影子根目录(适用于 Selenium 4.1 和最新的 Chromium 浏览器):
host_el = driver.find_element(By.CSS_SELECTOR, '.easepick-wrapper')
shadow_root = host_el.shadow_root
day = shadow_root.find_element(By.CSS_SELECTOR, '[data-time="1699225200000"]')
您也可以在浏览器控制台中尝试此操作,以下查询选择器将返回 null:
document.querySelector('[data-time="1699225200000"]')
这将返回以下元素:
document.querySelector('.easepick-wrapper').shadowRoot.querySelector('[data-time="1699225200000"]')
评论