Created
September 12, 2019 10:38
-
-
Save infloop/a4f17407ce30d1f0be5165471f84be5f to your computer and use it in GitHub Desktop.
Yandex click on all links
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {Builder, By, until} = require('selenium-webdriver'); | |
(async function yandexTest() { | |
let driver = await new Builder().forBrowser('chrome').build(); | |
try { | |
await driver.get('http://yandex.ru'); | |
// индекс текущей ссылки | |
let currentLinkIndex = 0; | |
// главный открытый таб в браузере | |
const mainTab = await driver.getWindowHandle(); | |
// переводим окно на полный экран | |
await driver.manage().window().maximize(); | |
while (true) { | |
const currentUrl = await driver.getCurrentUrl(); | |
// если мы не на главной яндекса - возвращаемся назад | |
if (currentUrl !== 'https://yandex.ru/') { | |
await driver.navigate().back(); | |
} | |
// ждем 2с когда URL страницы будет yandex.ru | |
await driver.wait(until.urlIs('https://yandex.ru/'), 2000); | |
// ищем все ссылки | |
const links = await driver.findElements(By.css('a')); | |
console.log('total links found', links.length); | |
// находим текущую ссылку по индексу | |
const link = links[currentLinkIndex]; | |
// если ссылки на странице закончились - выходим из цикла | |
if (currentLinkIndex > links.length - 1) { | |
break; | |
} | |
currentLinkIndex++; | |
if (!link) { | |
continue; | |
} | |
const href = await link.getAttribute('href'); | |
const isDisplayed = await link.isDisplayed(); | |
// если ссылка не имеет href или не видна пользователю, то пропускаем | |
if (!href || !isDisplayed) { | |
console.log('skipping this link, because it is not a link'); | |
continue; | |
} | |
console.log('clicking on ', href); | |
// кликаем по ссылке | |
driver.executeScript("arguments[0].click();", link); | |
// находим все открытые табы в браузере | |
let tabs = await driver.getAllWindowHandles(); | |
console.log('tabs', tabs.length); | |
// если открылся новый таб - закрываем его и переходим к главному табу | |
if (tabs.length > 1) { | |
await driver.switchTo().window(tabs[1]); | |
await driver.close(); | |
await driver.switchTo().window(mainTab); | |
} | |
} | |
} finally { | |
await driver.quit(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment