soup

repository·main·Indexed 22 days ago

https://github.com/anaskhan96/soup

A lightweight web scraping package for Go with an interface similar to Python's BeautifulSoup. It provides utilities to fetch HTML via GET and POST requests, parse HTML into a DOM tree using the Root struct, and navigate or query elements using methods like Find, FindAll, and Children. It includes support for custom HTTP clients, global header/cookie configuration, and a debug mode for error handling.

Tokens
1.9K
Snippets
3
Records
14
Agent score
31%

What's inside soup

  1. Understand the Root struct and Error handling

    main

    The Root struct is the primary object returned by parsing and DOM navigation methods. It contains:

    • Pointer: The pointer to the current HTML node.
    • NodeValue: The current node's value (tag name for ElementNode, text for TextNode).
    • Error: An error object if an operation failed, otherwise nil.

    If Error is not nil, you can check the Type field (of type ErrorType) to identify the specific issue. Supported error types include:

    • ErrUnableToParse
    • ErrElementNotFound
    • ErrNoNextSibling / ErrNoPreviousSibling / ErrNoNextElementSibling / ErrNoPreviousElementSibling
    • ErrCreatingGetRequest / ErrInGetRequest / ErrReadingResponse
  2. Scrape text and links from a website

    main

    This example demonstrates the full workflow: fetching a page, parsing it, finding a specific container, and iterating through its children to extract text and attributes.

    package main
    
    import (
    	"fmt"
    	"github.com/anaskhan96/soup"
    	"os"
    )
    
    func main() {
    	resp, err := soup.Get("https://xkcd.com")
    	if err != nil {
    		os.Exit(1)
    	}
    	doc := soup.HTMLParse(resp)
    	links := doc.Find("div", "id", "comicLinks").FindAll("a")
    	for _, link := range links {
    		fmt.Println(link.Text(), "| Link :", link.Attrs()["href"])
    	}
    }
  3. Fetch HTML content with Get and Post

    main

    Use the following functions to perform HTTP requests and retrieve HTML strings:

    • Get(url string) (string, error): Fetches the HTML content of the provided URL.
    • GetWithClient(url string, client *http.Client): Fetches HTML using a custom *http.Client.
    • Post(url string, bodyType string, payload interface{}) (string, error): Sends a POST request with a specified bodyType and payload.
    • PostForm(url string, body url.Values): Sends a POST request with application/x-www-form-urlencoded content type.

    To configure request headers or cookies globally before making a request, use the Headers and Cookies maps, or use the individual setter functions:

  4. Parse HTML and navigate the DOM with soup

    main

    After fetching HTML, use HTMLParse(html string) to return a Root struct, which represents a node in the DOM. You can then navigate and query the DOM using these methods on a Root object:

    Finding Elements

    • Find(tag string, attrKey string, attrVal string) Root: Returns the first occurrence matching the tag and attribute pair.
    • FindAll(tag string, attrKey string, attrVal string) []Root: Returns all occurrences matching the criteria.
    • FindStrict(...) and FindAllStrict(...): Performs exact matching for attribute values.

    DOM Navigation

    • Children() []Root: Returns all direct children of the current element.
    • FindNextSibling() Root: Returns the next sibling node.
    • FindNextElementSibling() Root: Returns the next sibling that is an element.
    • FindPrevSibling() Root: Returns the previous sibling node.
    • FindPrevElementSibling() Root: Returns the previous sibling that is an element.

    Extracting Data

    • Text() string: Returns the text inside a non-nested tag (returns only the first half if the tag contains nested elements).
    • FullText() string: Returns the complete text content inside a tag, including nested text.
    • Attrs() map[string]string: Returns a map of all attributes for the element.
    • HTML() string: Returns the raw HTML code for the specific element.
  5. Find elements in the DOM

    main

    Once you have a Root object, you can navigate the DOM using several methods:

    • Find(args ...string): Finds the first occurrence of a tag. You can optionally provide attribute names and values (e.g., Find("div", "class", "container")).
    • FindAll(args ...string): Returns a slice of all matching Root elements.
    • FindStrict(args ...string): Finds the first occurrence where all provided attributes are an exact match.
    • FindAllStrict(args ...string): Returns a slice of all matching elements with exact attribute matches.

    Arguments follow the pattern: tagName, attributeName, attributeValue.

  6. Enable debug mode

    main
    By default, errors are returned in the Error field of the returned structs. If you call SetDebug(true), the package will instead panic and log errors to the console. This is useful for rapid development and seeing exactly where a scraper fails.
  7. Perform HTTP GET requests

    main
    Use Get(url string) to perform a simple GET request using the default HTTP client. For more control, use GetWithClient(url string, client *http.Client) to provide your own *http.Client (e.g., for custom timeouts or transport settings). Both functions return the HTML response as a string or an error.
  8. Navigate DOM relationships

    main

    Navigate relative to a specific Root element using these methods:

    • Children(): Returns a slice of all direct children.
    • FindNextSibling(): Returns the next sibling node.
    • FindPrevSibling(): Returns the previous sibling node.
    • FindNextElementSibling(): Returns the next sibling that is an ElementNode (skipping text/comment nodes).
    • FindPrevElementSibling(): Returns the previous sibling that is an ElementNode (skipping text/comment nodes).
  9. Perform HTTP POST requests

    main

    Use Post(url string, bodyType string, body interface{}) to perform a POST request using the default client. The body can be a map[string]string (serialized to JSON), netURL.Values (form encoded), []byte (JSON), or string (JSON).

    For convenience with form data, use PostForm(url string, data netURL.Values).

    For advanced usage, PostWithClient(url string, bodyType string, body interface{}, client *http.Client) allows providing a custom client.

  10. Configure HTTP headers and cookies

    main
    Before making requests, you can configure global headers and cookies that will be attached to all subsequent requests made via the default client using Header(n string, v string) and Cookie(n string, v string).
  11. Parse HTML into a DOM tree

    main
    Use HTMLParse(s string) to convert an HTML string into a Root object. The Root object acts as the entry point for navigating and querying the DOM tree. If parsing fails, the returned Root will contain an error.