Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Equivalent to Javascript querySelector

In the Google Chrome's Inspect element tool you can: right-click on an element > copy > copy js path and you get a nice snippet of code like the following: document.querySelector("#left-container > div.left-content > div > div > ul") that easily gives you the "path" to a selected element in Javascript.

My question is if there is an easy way to turn this javascript snippet into Python possibly using BeautifulSoup that can give me the elements I want from a webpage.

like image 548
Anson Biggs Avatar asked Dec 24 '19 22:12

Anson Biggs


People also ask

How do you use querySelector in Python?

In the Google Chrome's Inspect element tool you can: right-click on an element > copy > copy js path and you get a nice snippet of code like the following: document. querySelector("#left-container > div. left-content > div > div > ul") that easily gives you the "path" to a selected element in Javascript.

What can I use instead of querySelector?

The other alternative is element. query / queryAll . These are alternative methods to querySelector and querySelectorAll that exist on DOM parent nodes. They also take selectors, except these selectors are interpreted relative to the element being queried from.

Is querySelector the same as getElementById?

getElementById matches the id attributes to find DOM nodes, while querySelector searches by selectors. So for an invalid selector e.g <div id="1"></div> , getElementById('1') would work while querySelector('#1') would fail, unless you tell it to match the id attribute (e.g querySelector('[id="1"]') .

Is querySelector JavaScript or jQuery?

querySelector() and querySelectorAll() are two jQuery functions which helps the HTML elements to be passed as a parameter by using CSS selectors ('id', 'class') can be selected.


1 Answers

BeautifulSoup has CSS selectors support - use select() or select_one() methods:

soup = BeautifulSoup(html, 'html.parser')
elements = soup.select("#left-container > div.left-content > div > div > ul")

Make sure to use version 4.7.0 or above to have support for the most CSS4 selectors.

like image 92
alecxe Avatar answered Sep 28 '22 05:09

alecxe