Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract ids and classes from a webpage using python?

This is my code so far :

import urllib2
with urllib2.urlopen("https://quora.com") as response:
    html = response.read()

I am new to Python and somehow I am successful in fetching the webpage, now how to extract ids and classes from the webpage?

like image 234
ddvb Avatar asked Aug 31 '26 20:08

ddvb


1 Answers

A better way to do so would be using the BeautifulSoup (bs4) web-scraping library, and requests.

After having installed both using pip, you can start as so:

import requests 
from bs4 import BeautifulSoup

r = requests.get("http://quora.com")
soup = BeautifulSoup(r.content, "html.parser")

To find an element with a specific id:

soup.find(id="your_id")

To find all elements with the "Answer" class:

soup.find_all(class_="Answer")

You can then use .get_text() to remove the html tags and use python string operations to organize your data.

like image 152
TrakJohnson Avatar answered Sep 02 '26 09:09

TrakJohnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!