Last modified: Jan 10, 2023 By Alexander Williams
Beautifulsoup: How to Select ID
To select a specific attribute in Beautifulsoup, we can use select() or select_one(). In this topic, we'll learn how to select by ID using select() or select_one().
Select ID using select()
select() is a method used to find all elements by a given CSS selector. in the following example, we'll use select() to select by ID.
from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module
# 👇 HTML Source
my_html = '''
<div id="node">
<p>Hello BeautifulSoup</p>
</div>
'''
soup = BeautifulSoup(my_html, 'html.parser') # 👉️ Parsing
el = soup.select("#node") # 👉️ Select All by ID
print(el) # 👉️ Result
Output:
[<div id="node">
<p>Hello BeautifulSoup</p>
</div>]
Also, you can select by ID and tag, as in the following example.
from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module
# 👇 HTML Source
my_html = '''
<div id="node">
<p>Hello BeautifulSoup</p>
</div>
'''
soup = BeautifulSoup(my_html, 'html.parser') # 👉️ Parsing
el = soup.select("#node p") # 👉️ Select All by ID and Tag
print(el) # 👉️ Result
Output:
[<p>Hello BeautifulSoup</p>]
Select ID using select_one()
select_one() is a method used to find the first element by a given CSS selector. Let's see an example of selecting ID.
from bs4 import BeautifulSoup # 👉️ Import BeautifulSoup module
# 👇 HTML Source
my_html = '''
<div id="node">
<p>Hello BeautifulSoup</p>
</div>
'''
soup = BeautifulSoup(my_html, 'html.parser') # 👉️ Parsing
el = soup.select_one("#node") # 👉️ Select One by ID
print(el) # 👉️ Result
Output:
<div id="node">
<p>Hello BeautifulSoup</p>
</div>