W
W
weranda2021-02-28 22:04:01
Google
weranda, 2021-02-28 22:04:01

How to open Google search results in JS?

Greetings.

Situation. It is necessary to make a bookmark in the browser in such a way that when you click on it, it opens the first 5 results of the Google PS, but I have not encountered this before and managed to do this:

javascript:(
    document.querySelectorAll('.g > div > div > a').forEach(link => link.click())
)()

But only the first page opens, and you need to make sure that five of them or another specified number open.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim, 2021-03-01
@weranda

Well, they would immediately write in the question about bookmarklets.
detail:

javascript:(
  Array.from(document.querySelectorAll('#rso > div:last-child a[data-ved]:not([id])')) // находим подходящие ссылки. Все у которых есть атрибут data-ved и нет id и лежат в последнем диве у элемента с id = rso
    .slice(0, 5) // режем до первых 5ти
    .forEach(i => window.open(i.href, '_blank')) // Открываем. Нужно будет разрешить открытие всплывающих окон в браузере. Иначе откроет только 1.
)(); void 0;

For bookmark:
javascript:(Array.from(document.querySelectorAll('#rso > div:last-child a[data-ved]:not([id])')).slice(0, 5).forEach(i => window.open(i.href, '_blank')))(); void 0;

Since the classes there are obfuscated and most likely change every build, you can only rely on the DOM structure, and I made the assumption that you can rely on id too, since they look like they will always be like that. But if the structure changes, it will be necessary to make changes.
PS uses Array.from methods and arrow functions which don't work in older browsers. But how to replace them is easy to google.

S
Sopromat4ik, 2021-03-18
@Sopromat4ik

thanks for the code. modified to unload top urls. I really needed to get them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question