Mar 28, 2019 06:22 PM
(This post was last modified: Mar 28, 2019 06:22 PM by AeroBlue.)
Introduction
What is Bs4?
Modules Used:
Step 1: Getting the page
If you need more help on using requests, please see Nachzehrer's Awesome Guide
Step 2: Parsing the page
Method 1: Find using soup.find() or soup.find_all()
Method 2: Find using soup.select()
Useful Links
Aero Wrote:This guide took me way longer than I anticipated so I will probably be adding more info later on. All feedback is welcome and appreciated, I am also willing to help anyone with questions they have regarding this post or bs4 / requests in general. I still don't really like the format of this post but I can't really think of a better way lol. Definitely my most HQ post I've ever made on HF, although that's not really saying much... Hope I can help a few people learn this amazing combination for webscraping in python!
What is Bs4?
Quote:Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching and modifying the parse tree. It commonly saves programmers hours or days of work.
Modules Used:
- Requests
Codepip install requests - Bs4
Codepip install bs4 - Bs4 and requests both require python 3 (3.6 recommended)
Step 1: Getting the page
Code
url = "https://example.com/"
r = requests.get(url)
page = r.text
soup = Beautifulsoup(page, "html.parser")
print(soup.prettify())Code
Result: "<html>...</html>"Step 2: Parsing the page
Method 1: Find using soup.find() or soup.find_all()
- Finding all links on a page using soup.find_all()
CodeExample HTML: <a href="example.com">Somelink</a>, <a href="otherlink.net">Otherlink</a>
Codelinks = [link.get("href") for link in soup.find_all("a")]
print(links)
CodeResult: "example.com","otherlink.net",etc.
- Finding text in first <p> tag using soup.find()
CodeExample HTML: <p>This is not the text you are looking for!</p>
Codeparagraph = soup.find("p").text
print(paragraph)
CodeResult: "This is not the text you are looking for!"
Method 2: Find using soup.select()
- Finding by class
CodeExample HTML: <p class="comment">Text to scrape</p>
Codeprint(soup.select(".comment")) #make sure you are finding the right information
comments = [comment.text for comment in soup.select(".comment")] #Get text for all comments on page
print(comments)
CodeResult: "Text to scrape","other comment","more comments","etc"
- Finding by tags
CodeExample HTML: <p><span>Random text to find</span></p>
Codeprint(soup.select("p > span"))
blocks = [block.text for block in soup.select("p > span")]
print(blocks)
CodeResult: "Random text to find", "another block of text"
- Finding by id
CodeExample HTML: <p><span id="comments">Comments, yay!</span></p>
Codesoup.select("#comments") OR soup.select("p > #comments")
comment_list = [comment.text for comment in soup.select("#comments")]
print(comment_list)
CodeResult: "comments, yay!", "comments are dumb", "more comments"
Useful Links


