Skip to content

Attributes

BeautifulSoup — read a tag attribute (CSRF token, id, href)

find(tag, {attribute: value}) searches the parsed document in order and returns the first matching element object. Indexing that object with an attribute name, such as ["value"] or ["href"], returns the corresponding HTML attribute string.

from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text, "html.parser")

csrf_element = soup.find("input", {"id": "csrf"})
csrf = csrf_element["value"]

name_element = soup.find("input", {"name": "csrf"})
name = name_element["value"]

link_element = soup.find("a", {"target": "_blank"})
href = link_element["href"]

button_element = soup.find("button", {"class": "delete-btn"})
file_id = button_element["value"]
file_id = file_id.strip()

Markup these calls target

<input id="csrf" name="csrf" value="9f8a1c">
<a target="_blank" href="/files/report.pdf">Open</a>
<button class="delete-btn" value="42">Delete</button>

What each variable holds

csrf -> "9f8a1c"
name -> "9f8a1c"
href -> "/files/report.pdf"
file_id -> "42"

Find by: beautifulsoup, bs4, attribute, value, csrf token, hidden input, href, find by id, find by name, find by class, scrape token, grab id · Source: PG/Monster, WSA, PG/Zipper, PG/WallpaperHub