w3resource

Python BeautifulSoup: Print the element(s) that has a specified id of a given web page

BeautifulSoup: Exercise-19 with Solution

Write a Python program to print the element(s) that has a specified id of a given web page.

Sample Solution:

Python Code:

import requests
import re
from bs4 import BeautifulSoup
url = 'https://www.python.org/'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'lxml')
print("\nelement(s) that has #python-network id:\n")
print(soup.select_one("#python-network"))

Sample Output:

element(s) that has #python-network id:

<a aria-hidden="true" class="jump-link" href="#top" id="python-network">
<span aria-hidden="true" class="icon-arrow-up"><span>▲</span></span> The Python Network
</a>

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to print content of elements that contain a specified string of a given web page.
Next: Write a Python program to create a Beautiful Soup parse tree into a nicely formatted Unicode string, with a separate line for each HTML/XML tag and string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Combining two iterable of tuples or pivot nested iterables:

# Combining two iterables
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]

# Pivoting list of tuples
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]