我正在尝试获取属性"onclick";(onclick="openDirection( 41.051777,28.986551)"
(。我想打印所有坐标。在上面的代码中,我可以打印前两个元素的坐标。但是,随后会抛出一个NoSuchElementException
。
driver.get('https://migroskurumsal.com/magazalarimiz/')
try:
select = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, 'stores'))
)
print('Dropdown is ready!')
except TimeoutException:
print('Took too much time!')
select = Select(driver.find_element(By.ID, 'stores'))
select.select_by_value('2')
shopList = driver.find_element(By.ID, "shopList")
try:
WebDriverWait(driver, 10).until(
EC.visibility_of_all_elements_located((By.XPATH, "//ul[@id='shopList']/li/div/button"))
)
print('Shoplist is ready!')
except TimeoutException:
print('Took too much time!')
driver.quit()
print(shopList.get_attribute("class"))
li_items = shopList.find_elements(By.TAG_NAME, 'li')
for item in li_items:
first = item.find_element(By.TAG_NAME, 'div')
second = first.find_element(By.TAG_NAME, 'button')
coord = second.get_attribute("onclick")
print(coord)
这里有几个问题:
- 您使用了错误的定位器
- 您需要滚动页面才能访问最初不在可见视图中的元素
这应该会更好地工作:
from selenium.webdriver.common.action_chains import ActionChains
driver.get('https://migroskurumsal.com/magazalarimiz/')
actions = ActionChains(driver)
try:
select = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'stores')))
print('Dropdown is ready!')
except TimeoutException:
print('Took too much time!')
select = Select(driver.find_element(By.ID, 'stores'))
select.select_by_value('2')
shopList = driver.find_element(By.ID, "shopList")
try:
WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@id='shopList']/li/div/button")))
time.sleep(1)
print('Shoplist is ready!')
except TimeoutException:
print('Took too much time!')
driver.quit()
li_items = shopList.find_elements(By.CSS_SELECTOR, 'li.m-bg-cream')
for idx, val in enumerate(li_items):
li_items = shopList.find_elements(By.CSS_SELECTOR, 'li.m-bg-cream')
item = li_items[idx]
actions.move_to_element(item).perform()
time.sleep(0.5)
button = item..find_elements(By.CSS_SELECTOR, "button[onclick^='set']")
coord = button.get_attribute("onclick")
print(coord)