![]() |
|
[Tut] Searching The Parse Tree Using BeautifulSoup - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Searching The Parse Tree Using BeautifulSoup (/thread-98554.html) |
[Tut] Searching The Parse Tree Using BeautifulSoup - xSicKxBot - 12-01-2020 Searching The Parse Tree Using BeautifulSoup Introduction HTML (Hypertext Markup Language) consists of numerous tags and the data we need to extract lies inside those tags. Thus we need to find the right tags to extract what we need. Now, how do we find the right tags? We can do so with the help of Code: BeautifulSoup'sBeautiful Soup has numerous methods for searching a parse tree. The two most popular and commonly methods are:
The other methods are quite similar in terms of their usage. Therefore, we will be focusing on the Code: find()Code: find_all() The following Example will be used throughout this document while demonstrating the concepts:Code: html_doc = """ <html><head><title>Searching Tree</title></head>
<body>
<h1>Searching Parse Tree In BeautifulSoup</h1></p> <p class="Main">Learning <a href="https://docs.python.org/3/" class="language" id="python">Python</a>,
<a href="https://docs.oracle.com/en/java/" class="language" id="java">Java</a> and
<a href="https://golang.org/doc/" class="language" id="golang">Golang</a>;
is fun!</p> <p class="Secondary"><b>Please subscribe!</b></p>
<p class="Secondary" id= "finxter"><b>copyright - FINXTER</b></p> """
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, "html.parser")There are different filters that can be passed into the Code: find()Code: find_all()
❖ A String When we pass a string to a search method then Beautiful Soup performs a match against that passed string. Let us have a look at an example and find the <h1> tags in the HTML document: Code: print(soup.find_all('h1'))Output: Code: [<h1>Searching Parse Tree In BeautifulSoup</h1>]Passing a regular expression object allows Beautiful Soup to filter results according to that regular expression. In case you want to master the concepts of the regex module in Python, please refer to our tutorial here. Note:
Example: The following code finds all instances of the tags starting with the letter “b”. Code: # finding regular expressions
for regular in soup.find_all(re.compile("^b")): print(regular.name)Output: Code: body
bMultiple tags can be passed into the search functions using a list a shown in the example below: Example: The following code finds all the <a> and <b> tags in the HTML document. Code: for tag in soup.find_all(['a','b']): print(tag)Output: Code: <a class="language" href="https://docs.python.org/3/" id="python">Python</a>
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a>
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>
<b>Please subscribe!</b>We can define a function and pass an element as its argument. The function returns Code: TrueCode: FalseExample: The following code defines a function which returns Code: TrueCode: classesCode: idCode: find_all()Code: def func(tag): return tag.has_attr('class') and tag.has_attr('id') for tag in soup.find_all(func): print(tag)Output: Code: <a class="language" href="https://docs.python.org/3/" id="python">Python</a>
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a>
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>➠ Now that we have gone through the different kind of filters that we use with the search methods, we are well equipped to dive deep into the Code: find()Code: find_all() The find() MethodThe Code: find()Syntax: Code: find(name, attrs, recursive, string, **kwargs)➠ Code: find()Example: Code: print(soup.find('h1'), "\n")
print("RETURN TYPE OF find(): ",type(soup.find('h1')), "\n")
# note that only the first instance of the tag is returned
print(soup.find('a'))Output: Code: <h1>Searching Parse Tree In BeautifulSoup</h1> RETURN TYPE OF find(): <class 'bs4.element.Tag'> <a class="language" href="https://docs.python.org/3/" id="python">Python</a>➠ The above operation is the same as done by the Code: soup.h1Code: soup.aCode: find()Code: print(soup.find('a',id='golang'))Output: Code: <a class="language" href="https://golang.org/doc/" id="golang">Golang</a> The find_all() MethodWe saw that the Code: find()Code: find_all()Syntax: Code: find_all(name, attrs, recursive, string, limit, **kwargs)Example: Searching all instances of the ‘a’ tag in the HTML document. Code: for tag in soup.find_all('a'): print(tag)Output: Code: <a class="language" href="https://docs.python.org/3/" id="python">Python</a>
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a>
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>Now there are numerous other argument apart from the filters that we already discussed earlier. Let us have a look at them one by one. ❖ The name Argument As stated earlier the name argument can be a string, a regular expression, a list, a function, or the value True. Example: Code: for tag in soup.find_all('p'): print(tag)Output: Code: <p class="Main">Learning <a class="language" href="https://docs.python.org/3/" id="python">Python</a>,
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a> and
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>;
is fun!</p>
<p class="Secondary"><b>Please subscribe!</b></p>Just like the Code: find()Code: find_all()Code: idExample: Code: print(soup.find_all('a',id='java'))Output: Code: [<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a>]You can also pass the attributes as dictionary key-value pairs using the Code: attrsExample: Code: print(soup.find_all('a', attrs={'id': 'java'}))Output: Code: [<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a>]Often we need to find a tag that has a certain CSS class, but the attribute, Code: classCode: classCode: class_Example: Code: print(soup.find_all('p', class_='Secondary'))Output: Code: [<p class="Secondary"><b>Please subscribe!</b></p>]❖ Note: The above search will allow you to search all instances of the p tag with the class “Secondary” . But you can also filter searches based on multiple attributes, using a dictionary. Example: Code: print(soup.find_all('p', attrs={'class': 'Secondary', 'id': 'finxter'}))Output: Code: [<p class="Secondary" id="finxter"><b>copyright - FINXTER</b></p>]The string argument allows us to search for strings instead of tags. Example: Code: print(soup.find_all(string=["Python", "Java", "Golang"]))Output: Code: ['Python', 'Java', 'Golang']The Code: find_all()Code: limitExample: There are three links in the example HTML document, but this code only finds the first two: Code: print(soup.find_all("a", limit=2))Output: Code: [<a class="language" href="https://docs.python.org/3/" id="python">Python</a>, <a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a>] Other Search MethodsWe have successfully explored the most commonly used search methods, i.e., Code: findCode: find_all()
Example: Code: current = soup.find('a', id='java')
print(current.find_parent())
print()
print(current.find_parents())
print()
print(current.find_previous_sibling())
print()
print(current.find_previous_siblings())
print()
print(current.find_next())
print()
print(current.find_all_next())
print()Output: Code: <p class="Main">Learning <a class="language" href="https://docs.python.org/3/" id="python">Python</a>,
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a> and
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>;
is fun!</p> [<p class="Main">Learning <a class="language" href="https://docs.python.org/3/" id="python">Python</a>,
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a> and
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>;
is fun!</p>, <body>
<h1>Searching Parse Tree In BeautifulSoup</h1>
<p class="Main">Learning <a class="language" href="https://docs.python.org/3/" id="python">Python</a>,
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a> and
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>;
is fun!</p>
<p class="Secondary"><b>Please subscribe!</b></p>
<p class="Secondary" id="finxter"><b>copyright - FINXTER</b></p>
<p class="Secondary"><b>Please subscribe!</b></p>
</body>, <html><head><title>Searching Tree</title></head>
<body>
<h1>Searching Parse Tree In BeautifulSoup</h1>
<p class="Main">Learning <a class="language" href="https://docs.python.org/3/" id="python">Python</a>,
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a> and
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>;
is fun!</p>
<p class="Secondary"><b>Please subscribe!</b></p>
<p class="Secondary" id="finxter"><b>copyright - FINXTER</b></p>
<p class="Secondary"><b>Please subscribe!</b></p>
</body></html>, <html><head><title>Searching Tree</title></head>
<body>
<h1>Searching Parse Tree In BeautifulSoup</h1>
<p class="Main">Learning <a class="language" href="https://docs.python.org/3/" id="python">Python</a>,
<a class="language" href="https://docs.oracle.com/en/java/" id="java">Java</a> and
<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>;
is fun!</p>
<p class="Secondary"><b>Please subscribe!</b></p>
<p class="Secondary" id="finxter"><b>copyright - FINXTER</b></p>
<p class="Secondary"><b>Please subscribe!</b></p>
</body></html>] <a class="language" href="https://docs.python.org/3/" id="python">Python</a> [<a class="language" href="https://docs.python.org/3/" id="python">Python</a>] <a class="language" href="https://golang.org/doc/" id="golang">Golang</a> [<a class="language" href="https://golang.org/doc/" id="golang">Golang</a>, <p class="Secondary"><b>Please subscribe!</b></p>, <b>Please subscribe!</b>, <p class="Secondary" id="finxter"><b>copyright - FINXTER</b></p>, <b>copyright - FINXTER</b>, <p class="Secondary"><b>Please subscribe!</b></p>, <b>Please subscribe!</b>]With that we come to the end of this article; I hope that after reading this article you can search elements within a parse tree with ease! Please subscribe and stay tuned for more interesting articles. Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! The post Searching The Parse Tree Using BeautifulSoup first appeared on Finxter. |