Adding a retailer
Biryar ships with the shops it has been able to read. Your supplier is probably not one of them. This is how you add it.
This is the one guide here that expects you to write code, a small piece of Python. If that is not you, a developer can do it from this page in an afternoon. Adding a retailer is part of Pro.
An adapter is a class. It inherits from nothing, registers nothing, and is handed a page of HTML and asked for offers. Everything else (fetching, robots.txt, rate limiting, the scraping proxy, resuming where the last pass stopped, the Keepa lookup, the screening against your own measured Amazon fees) already exists and is not your problem.
Two ways to add one
Section titled “Two ways to add one”In Biryar. Under Settings, Sourcing, in the card Your own retailers, an owner chooses Add a retailer, pastes the class and presses Save. Biryar checks that it loads before keeping it, and says what is wrong when it does not. The retailer then appears in the list like the rest, marked “added by you”, and can be scanned and kept running like any other.
From a terminal, which is the quicker way to work while a parser is
still being got right. That is the loop below. On a Docker install, type
each command in the biryar folder with docker compose exec api in
front of it.
The loop
Section titled “The loop”python -m biryar.adapters new mybookshop --country GB --domain mybookshop.co.ukpython -m biryar.adapters check mybookshop --url https://mybookshop.co.uk/some-productnew writes adapters/mybookshop.py: a working adapter for a shop that
publishes schema.org JSON-LD, which most do. Run check against one
real product page before you change anything: if the shop is
conventional you are already finished.
When it reads nothing, check tells you which of the two things went
wrong, because they need opposite responses:
Fetched https://mybookshop.co.uk/some-product ok 200 · 574,844 bytes
parse() returned nothing from this page.That is a parser problem. This is not:
http_error 403 · 0 bytesThree modes, cheapest first:
| What it does | |
|---|---|
check <slug> --file saved.html --url <url> |
Reads a page off disk. No network, no scraping key, no database, no robots.txt. The loop for working on a parser. |
check <slug> --url <url> |
Fetches one page the way a scan does: robots.txt honoured, the retailer’s delay, your scraping key if the adapter asks for one. |
check <slug> |
Walks from the adapter’s own seeds() with a small page budget, exactly as a scan would, and prints the discovery as well as the offers. |
The third catches the faults that are not in parse() at all: a seed
that 404s, a sitemap index whose first child is 10,000 category pages,
a shop that answers one page and then refuses. Every one of those has
happened to a retailer in this repository.
Save the file and run it again: there is nothing to restart. The
registry is rebuilt whenever anything in adapters/ changes.
The interface
Section titled “The interface”class MyBookshop: slug = "mybookshop" name = "My Bookshop" country = "GB" domains = ("mybookshop.co.uk", "www.mybookshop.co.uk") needs_scraper = False
def seeds(self): ... def parse(self, page): ...slug |
Lowercase, digits and hyphens. Stored on every offer, so renaming it later orphans what this has already found. |
name |
What you call the shop. |
country |
ISO 3166-1, two capitals. Decides the currency and whether a shelf price is understood to include consumer tax. |
domains |
Every hostname this claims. A tuple: a bare string makes each of its letters a hostname, which is why that is refused. Two adapters cannot claim one host. |
needs_scraper |
True if the shop refuses an ordinary request. Costs you credits on every page, so leave it False until you have watched it refuse. |
seeds() |
Where a scan starts. Usually one sitemap. |
parse(page) |
page.url, page.html, page.fetched_at. Return or yield Offers. |
parse gets the HTML and the URL and nothing else: no client, no
credentials, no database. That is not tidiness: it is what makes
running your own code here a reasonable thing to do, and it is enforced
by what Page does not carry.
Optional, and read if present
Section titled “Optional, and read if present”wants_sitemap(url) -> bool |
Which sitemaps are worth opening. A large shop’s index is mostly images, categories and editorial; without this a pass can spend thousands of pages on documents that cannot hold an offer. |
request_delay |
Seconds between requests. Only ever slower than the install’s setting: an adapter may say a shop needs more room, never that it needs less. |
scraper_options |
Extra proxy options the shop needs, e.g. {"render": "true"}. Declared rather than switched on hopefully, because each one multiplies what a page costs you. |
A worked example
Section titled “A worked example”Medimops sells used books, CDs and DVDs. It ships with Biryar, and its
adapter is the one to read first, because it is conventional in the way
most shops are: the price and the condition are in schema.org JSON-LD,
and the barcode is not. This is the whole of it, written the way you
would write your own. A shop you add needs a slug, a name and
domains of its own; a slug that a shipped shop already has is refused.
import re
from biryar.sourcing import Condition, Offer, Page, barcode, schema_org
#: ``ISBN / EAN:`` and its value, from the product-details table.EAN = re.compile( r"ISBN\s*/\s*EAN:\s*</dt>\s*<dd[^>]*>\s*([0-9\s-]+?)\s*</dd>", re.IGNORECASE,)
class Medimops: slug = "medimops" name = "Medimops" country = "DE" domains = ("medimops.de", "www.medimops.de") # It answered a plain request at first. Then six of nine direct page # reads came back 403, so it says what it needs rather than failing # for some pages and not others. needs_scraper = True
def seeds(self): return ["https://www.medimops.de/sitemap_index_deu.xml"]
def wants_sitemap(self, url: str) -> bool: # The index lists 160 children, one of which is categories. return "sitemap_product" in url
def parse(self, page: Page): stated = EAN.search(page.html) if stated is None: return # not a product page gtin = barcode.read(stated.group(1)) if not gtin: return # or not a real barcode
for node in schema_org.products(schema_org.blocks(page.html)): listing = schema_org.first_offer(node) price = schema_org.price(listing) title = str(node.get("name") or "").strip() if not title or price is None: continue if not schema_org.buyable(listing): continue
yield Offer( retailer=self.slug, url=page.url, title=title, sku=gtin, price=price, currency=str(listing.get("priceCurrency") or "EUR"), gtin=gtin, brand=schema_org.brand(node), image_url=schema_org.first_image(node), # Read, not assumed: this shop sells used and new, and # says which. Used is its default, because a used copy # screened against Amazon's New buy box is a loss # wearing a margin. condition=schema_org.condition(listing, Condition.USED), in_stock=True, price_includes_tax=True, # a German shelf price does )Two things in there are worth copying, and one is worth noticing.
The barcode is read from the label, not from the class. The real markup is
<dt class="ProductAttributes_rowDefinition__8PGYQ">ISBN / EAN:</dt><dd class="ProductAttributes_rowValue__fWL3F">9781848125582</dd>and __8PGYQ is generated at build time. An adapter keyed on it stops
finding barcodes after the shop’s next deploy without stopping
working: pages read, offers dropped, no error anywhere. The label is
the part a person maintains, so it is the part to match.
barcode.read is used rather than the string itself. A number in a
field called EAN is not an EAN until its check digit says so.
And a missing barcode returns rather than guessing. That is what makes the adapter safe to point at a whole sitemap: anything that is not a product page simply yields nothing.
What an offer has to get right
Section titled “What an offer has to get right”Offer( retailer=self.slug, url=page.url, title="…", sku="…", price=Decimal("16.99"), currency="GBP", gtin="5054061482232", condition=Condition.NEW, in_stock=True, price_includes_tax=True,)Four of these decide whether a candidate is right, wrong, or quietly dropped. They are worth more attention than the parsing.
gtin: no barcode, no candidate. It is the only reliable route to
an Amazon listing; title-and-image matching is slower and wrong more
often, so an offer without one is skipped before a paid lookup is spent
on it. It is also checked: a GTIN carries its own check digit, and a
number that fails is treated as no barcode at all. One shipped retailer
publishes its own article number in gtin13 on about one product in
six, and eight digits is a legal GTIN-8 length, so nothing but the check
digit tells them apart.
condition: the default is UNSTATED, and that is not NEW. The
screening step refuses to compare an unstated condition with Amazon’s
New buy box, so forgetting this gives you a scan that reads pages, spends
lookups and produces no candidates, with condition_mismatch in the run
report to say why. Read it from the page where the page says it. A used
book priced against the New buy box is a loss wearing a margin.
price_includes_tax: a German or British shelf price does; a United
States one does not. Getting it wrong moves every margin by the VAT
rate, which is why it is stated rather than guessed from the currency.
currency: read it from the page rather than assuming it from the
country. A British shop has answered this machine in US dollars. Fees
measured in one currency cannot price a listing in another, and the
screening step refuses rather than converting.
What the shipped retailers learned the hard way
Section titled “What the shipped retailers learned the hard way”Every one of these came from a real page, and every one of them failed quietly: a healthy 200 and an empty result, never an error.
Structured data lies about state. The rule that holds across all
eighteen is identity from the structured data, state from the page.
A Product block is a contract the shop maintains with search engines;
it is not kept in sync with the shelf. One retailer’s JSON-LD gives a
price that has since been marked down and an availability that
contradicts its own buy button. Another’s itemCondition is a constant
that says NewCondition on a shop that sells nothing new. Argos
publishes JSON-LD with no barcode and an availability of OutOfStock
for a product its own page state says is in stock and deliverable.
A dead product URL often answers 200. HMV serves the parent
category: twenty-five tiles, each with a name, a price and an
availability, none of them the product that was asked for. Read
naively that is twenty-five confident offers at other products’ prices.
Find something that is true of a product page and false of a listing
(there, exactly one <h1 itemprop="name"> and exactly one barcode row)
and yield nothing when it does not hold.
The first URLs in a sitemap are not a sample. They are clustered. One shop’s first 10,640 sitemap entries are all category pages; another’s begin with several thousand print-on-demand reprints. Judging a catalogue, or inventing a filter, from the top of a file is how a scan quietly loses most of a shop. Sample from the middle.
Several prices on a page, and the right one is not the first. A product page carries recommendations, other editions, bundles. Match the one that belongs to this page by something the URL states (an id, an ISBN) and check it against what the page says about itself. On one shop a recommendation happened to carry the same price as the product, which would have made “the first price on the page” look correct on exactly the page it was tested against.
Read the whole document before believing it is empty. A page can
publish its product as microdata attributes rather than JSON-LD, inside
a window.__data JavaScript object, in data- attributes on a buy
button, or in Open Graph meta tags. All four are in this repository
because all four were, at first, mistaken for a shop with nothing on it.
Where the files live
Section titled “Where the files live”On a Docker install, on a volume of their own called biryar-adapters,
which the program sees as /app/adapters. Whatever you save under
Settings lands there, and so does what adapters new writes. From a
source checkout it is the adapters/ folder, or wherever
BIRYAR_ADAPTERS_DIR points.
Every *.py in it is imported when a scan runs; names starting with _
are skipped, so notes and half-written things can sit there.
One file is one adapter’s worth of code. The directory is deliberately
not on sys.path, so an adapter cannot import a sibling file: a
directory on the path shadows standard-library modules by accident, and
a file called json.py in there would be a very confusing afternoon.
A file that does not load does not stop the others, and does not go
quiet either: the reason appears on the sourcing screen and in
python -m biryar.adapters list, which exits non-zero when anything
failed.
Updating Biryar does not touch your adapters. Keep a copy of anything you would be sorry to lose: the box under Settings shows the source of each one, ready to copy.
Only on your own machine
Section titled “Only on your own machine”Importing a file runs it. On a hosted deployment that means running one seller’s code inside a process that holds every other seller’s Amazon refresh token and an open database connection, and no review of an adapter’s interface changes that, because the damage is done at import, before any method is called.
So the directory is read on a self-hosted install and ignored
everywhere else, and the refusal happens before anything is imported.
Keeping parse pure is what leaves a sandboxed third option open
later.