A Level Computer Science · Chapter 12 · Component 01: Computer systems
A web page combines HTML for content, CSS for appearance and JavaScript for behaviour, while search engines index pages and rank them with algorithms such as PageRank.
This chapter teaches how browsers and servers communicate, how HTML and CSS build and style a page, and how JavaScript and server code share the work. It then teaches how search engines crawl, index and rank the web.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- explain how a browser requests a page from a web server using HTTP, and read a URL
- write HTML for headings, paragraphs, lists, links, images, divisions and forms
- write CSS rules with element, class and id selectors, and work out which rule wins by specificity
- use JavaScript to change a page and check a form, and compare client-side and server-side processing
- explain how a search engine crawls and indexes the web, and use an inverted index to answer a query
- calculate PageRank for a small set of pages, and explain why it ranks pages as it does
Time: three sessions, about 4 hours, plus the programming task.
You need first: networks and protocols from Networks, protocols and the internet, and programming constructs from Programming constructs.
The big picture
The big picture
The World Wide Web is a huge collection of linked documents and applications reached through the internet. It is not the same thing as the internet. The internet is the network of networks that carries data. The web is one of the services that runs on it, alongside email, video calls, online games and file sharing.
Every web page is built from three languages, each with its own job. HTML, the HyperText Markup Language, describes the content and its structure: this is a heading, this is a paragraph, this is a link. CSS, Cascading Style Sheets, describes how that content looks: its colours, fonts, sizes and layout. JavaScript is a programming language that runs in the browser and makes the page respond, for example by checking a form before it is sent.
Keeping the three separate is a deliberate design. A website can be restyled completely by changing only its CSS, without touching a word of its content. Screen readers for blind users can read the HTML's structure directly, ignoring the styling. And the same content can be laid out one way on a phone and another on a large screen.
The web also depends on open standards. The rules for HTML, CSS and JavaScript are published openly and agreed between browser makers, so a page written once works in every browser on every device. This is the same idea as the open protocols of the internet, and it is why anyone can publish a website without asking permission.
The web is so large that nobody could find anything without search engines. A search engine sends out programs that follow links from page to page and record which words appear on each one. From these it builds an index that can answer a query in a fraction of a second. Because a query may match millions of pages, the engine must also rank them, putting the most useful first. PageRank, the algorithm behind the first successful search engine of its kind, ranks pages by the links that point to them.
Section 1
How the web works
Requests and responses
The web works on the client–server model. The browser is the client; it sends a request, and a web server sends back a response. The two communicate using HTTP, the HyperText Transfer Protocol, or HTTPS, its encrypted form.
When a user types a web address or clicks a link, the browser first uses DNS to find the server's IP address. It then opens a connection to the server and sends an HTTP request. A GET request asks for a resource, such as a page or an image. A POST request sends data to the server, such as the contents of a form.
The server replies with a status code and the requested content. Code 200 means the request succeeded, 404 means the page was not found, and 500 means something went wrong on the server. The browser then reads the HTML, sees that it also needs a style sheet, a script and some images, and requests each of those in turn.
Common mistake: thinking the web and the internet are the same thing. The internet is the worldwide network that carries data between computers. The web is one service that uses it, made of pages linked together and reached with HTTP. Email and video calls use the internet too, but they are not part of the web.
URLs
A uniform resource locator, or URL, says exactly where a resource is and how to get it. In https://www.example-school.sch.uk/clubs/chess.html, the first part, https, is the protocol. Next comes the domain name of the server. Last comes the path to the resource on that server, here a file called chess.html in a folder called clubs.
A URL can also carry extra data after a question mark, called a query string, such as ?term=autumn. Servers use these values to decide what to send back, for example the timetable for a particular term.
Worked example 1: the requests a page makes
A page's HTML refers to one style sheet, two scripts and five images. How many HTTP requests does the browser make to load it? How long does it take if each round trip takes 40 ms and the requests are made one after another?
| Working | Reason |
|---|---|
| Requests = 1 + 1 + 2 + 5 = 9 | One for the HTML and one for each file it uses |
| Time = 9 × 40 = 360 ms | Each request waits for a whole round trip |
| Browsers make several requests at once to save time | They do not have to wait for each in turn |
| Fewer, larger files make pages load faster | Each request has its own delay |
Static and dynamic pages
A static page is stored on the server as a finished file and sent unchanged to everyone who asks for it. A dynamic page is built by the server when it is requested, often using data from a database. Most large websites are almost entirely dynamic, because every visitor sees a slightly different page, built from their own account, location and history. A school's homework page is dynamic: the server looks up the logged-in pupil's homework and builds a page just for them.
HTTP itself does not remember anything between requests: each request is handled on its own. To recognise a logged-in user from one page to the next, the server gives the browser a small piece of data called a cookie. The browser sends it back with every later request. Cookies are also used to remember settings and, more controversially, to track people across websites, which is why sites must ask permission to use many of them.
Browsers also keep copies of files they have already downloaded, in a cache. When the same page is visited again, unchanged images and style sheets are loaded from the cache instead of being requested again. Repeat visits are much faster, and the server is saved work.
Check yourself. In the URL https://www.example-school.sch.uk/clubs/chess.html, what are the protocol, the domain name and the path?
Show the answer
The protocol is https, the domain name is www.example-school.sch.uk and the path is /clubs/chess.html, a file called chess.html in the clubs folder.
Section 2
HTML
Elements and tags
HTML describes a page as a set of elements, each marked by tags. Most elements have an opening tag and a closing tag, with content between them. The paragraph element is written with an opening tag p in angle brackets, then the text, then a closing tag with a slash. Elements can contain other elements, so a page forms a tree.
Browsers are forgiving: if a closing tag is missing, they guess where the element was meant to end and display the page anyway. But their guesses can differ, so badly written HTML may look different in different browsers. Writing valid HTML, with every element opened and closed in the right order, makes a page reliable everywhere.
Every page has the same outer structure. The html element contains everything. Inside it, the head element holds information about the page, such as its title and the style sheets it uses, which is not shown in the page itself. The body element holds everything that is shown.
<!DOCTYPE html>
<html>
<head>
<title>Chess club</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Chess club</h1>
<p>We meet every <strong>Thursday</strong> at lunchtime.</p>
<ul>
<li>Beginners welcome</li>
<li>Tournament in March</li>
</ul>
<a href="clubs.html">All clubs</a>
<img src="board.jpg" alt="A chess board">
</body>
</html>
Common elements
Headings run from h1, the most important, down to h6. A page should normally have a single h1, its main title, with h2 and h3 headings marking its sections and subsections in order. The p element holds a paragraph. Lists are written with ul for a bulleted list or ol for a numbered one, with each item in an li element. The a element makes a hyperlink, and its href attribute gives the address it links to. The img element shows an image: its src attribute gives the image file, and its alt attribute gives text that describes the image for people who cannot see it.
The div element groups other elements into a block, so they can be styled or laid out together. The span element does the same for a run of text within a line. Forms collect input: the form element contains input elements, such as text boxes and buttons, and its action attribute says where the data is sent.
Tables of data are written with the table element, which contains a row element, tr, for each row, and data cells, td, inside each row. Tables should be used for data that really is a table, such as a timetable, and not for laying out a page, which is the job of CSS.
Attributes
Attributes give extra information about an element and are written inside its opening tag, as a name, an equals sign and a value in quotation marks. Two attributes matter for styling. A class attribute gives an element one or more class names, which many elements can share. An id attribute gives an element a unique name, which no other element on the page may use.
Common mistake: thinking HTML is a programming language. HTML only describes content and its structure. It has no variables, no decisions and no loops, so it cannot calculate anything or respond to the user by itself. That behaviour comes from JavaScript.
Worked example 2: reading HTML
In the chess club page, how many list items are there, and what does a screen reader say for the image?
| Working | Reason |
|---|---|
| The ul element contains two li elements | Each li is one list item |
| So there are 2 list items | Beginners welcome and Tournament in March |
| The img element has alt="A chess board" | The alt text describes the image |
| A screen reader reads out "A chess board" | Users who cannot see the image still learn what it shows |
Worked example 3: a form
Write HTML for a form that asks for a pupil's name and sends it to join.php.
| Working | Reason |
|---|---|
| A form element with action="join.php" | Sets where the data is sent |
| An input element with type="text" and name="pupil" | A text box whose value is sent as pupil |
| An input element with type="submit" | A button that sends the form |
| The browser sends pupil=Ava to join.php when Ava submits | The server receives the name and value |
Good HTML describes meaning, not appearance. A heading should be marked as a heading because it is one, not because the writer wants large bold text. Elements such as nav for a menu and footer for the end of a page describe what each part is for. Browsers, search engines and screen readers all use this information.
Check yourself. How does a class attribute differ from an id attribute?
Show the answer
Many elements can share the same class, but an id must be unique: only one element on a page may have a given id.
Section 3
CSS
Rules, selectors and properties
CSS describes how elements look. A style sheet is a list of rules. Each rule has a selector, which picks out the elements it applies to, and a block of declarations in curly brackets. Each declaration sets a property to a value, such as color: navy or font-size: 18px.
p { color: navy; font-size: 18px; }
.notice { background-color: lightyellow; }
#main-title { text-align: center; }
nav a { text-decoration: none; }
An element selector, such as p, applies to every element of that kind. A class selector starts with a full stop, such as .notice, and applies to every element with that class. An id selector starts with a hash, such as #main-title, and applies to the one element with that id. Selectors can be combined: nav a means every link inside a nav element.
Colours can be given by name, such as navy, or as hexadecimal codes, such as #1E3A5F. A code gives the amounts of red, green and blue as two hexadecimal digits each. Sizes can be given in pixels, as percentages of the surrounding box, or in units that grow with the text size. Choosing relative sizes helps a page adapt to different screens and to users who enlarge their text.
Where CSS goes
CSS can be written in three places. An external style sheet is a separate file linked from the head of every page, so a whole website shares one design and one change restyles every page. Internal CSS sits in a style element in the head of one page. Inline CSS is written in a style attribute on one element. External style sheets are usually best, because they keep the design in one place.
An external style sheet has another benefit: the browser downloads it once and keeps it in its cache. Every other page of the site that uses the same style sheet then loads faster, because only its HTML needs to be fetched. A large site may have thousands of pages but only a handful of style sheets.
The cascade and specificity
Often several rules set the same property of the same element. The browser then has to decide which rule wins. This decision is called the cascade, and it gives Cascading Style Sheets their name.
The main test is specificity: the more precisely a selector picks out an element, the more weight it has. Specificity is counted as three numbers: the number of id selectors, the number of class selectors and the number of element selectors. Two selectors are compared by their id counts first, then their class counts, then their element counts. Only if all three are equal does the rule written later win. Inline styles beat all of these.
Some properties are inherited. If a rule sets the font of the body element, every paragraph and heading inside the body uses that font too. That holds unless a more specific rule sets a different one. Inheritance means a whole page can be given a consistent look with a few rules near the top of the style sheet, with exceptions added only where needed.
Figure 12.1 shows two rules competing to colour the same paragraph. Add classes to the first rule and watch which one wins. Then switch on the wrong model.
The CSS cascade
- Rule 1 specificity
- (0, 0, 2)
- Rule 2 specificity
- (0, 1, 1)
- Winning rule
- 2
Common mistake: thinking the rule written last always wins. Order only decides between rules of equal specificity. A selector with more ids or classes wins even if it appears earlier in the style sheet, which is why a style sometimes seems to be ignored.
Worked example 4: counting specificity
Find the specificity of p, .card p, div.card p and #main p.
| Working | Reason |
|---|---|
| p: no ids, no classes, one element, so (0, 0, 1) | A single element selector |
| .card p: (0, 1, 1) | One class and one element |
| div.card p: (0, 1, 2) | One class and two elements |
| #main p: (1, 0, 1) | An id outweighs any number of classes |
Worked example 5: which rule wins?
The rules div.card p { color: teal } and, later, .card p { color: orange } both apply to a paragraph. Which colour is it?
| Working | Reason |
|---|---|
| div.card p has specificity (0, 1, 2) | One class and two elements |
| .card p has specificity (0, 1, 1) | One class and one element |
| Ids are equal and classes are equal, but 2 elements beat 1 | Compare the counts in order |
| The paragraph is teal, from the earlier rule | Specificity is checked before order |
Derivation: comparing specificities
Write the specificity of a selector as a triple, counting ids, classes and elements.
Two triples are compared like the digits of a number, from the left, so a single id beats any number of classes. For counts below ten, this is the same as comparing
So #main p, with v = 101, beats div.card.wide.dark p, with v = 32. When v is equal, the rule that comes later in the style sheet wins.
Layout and responsive design
CSS also controls layout: the size of each box, the space around it and where it sits. The box model describes every element as a content area surrounded by padding, a border and a margin. Modern layout tools arrange boxes in rows and columns that stretch to fit the screen.
Responsive design makes one page work on every screen size. Media queries apply different rules depending on the width of the screen. A menu that runs along the top on a laptop can then fold into a button on a phone. Because the content is in HTML and the layout in CSS, only the CSS needs to change.
Good design also means accessible design. Text must contrast enough with its background to be read by people with poor eyesight. The page must still make sense if a user enlarges the text or uses only a keyboard. Accessibility is a legal duty for many organisations, and it helps every user, not only those with disabilities.
Check yourself. Which wins: #menu a or nav ul li a? Explain.
Show the answer
The selector #menu a has specificity (1, 0, 1) and nav ul li a has (0, 0, 4). The id count is compared first, and 1 beats 0, so #menu a wins.
Section 4
JavaScript and processing
JavaScript in the browser
JavaScript is a programming language that runs inside the browser. It can respond to events, such as a click or a key press, change the page without reloading it, and check the user's input. It reaches the page's elements through the document object model, the tree of elements built from the HTML.
JavaScript programs are mostly event-driven. Instead of running from start to finish, they set up functions that wait for something to happen. That might be a button being clicked, a key being pressed or a page finishing loading. When the event happens, the browser calls the matching function. This suits a web page, where the program must respond to whatever the user decides to do next.
function checkForm() {
const age = Number(document.getElementById("age").value);
if (age < 11 || age > 18) {
document.getElementById("message").textContent = "Enter an age from 11 to 18";
return false;
}
return true;
}
This function reads the value typed in the element whose id is age and checks that it is in range. If not, it shows a message in another element and stops the form being sent. JavaScript can also add and remove elements, change their styles, and fetch new data from the server in the background. That is how a page can update a live score without being reloaded.
Client-side and server-side processing
Client-side processing happens in the browser, on the user's device. It uses the processor of the phone or laptop the page is open on, so a site with a million visitors has a million processors helping it. JavaScript checking a form, animating a menu or sorting a table are all client-side. It responds instantly, because there is no round trip to the server, and it reduces the load on the server, because each user's device does its own work.
Server-side processing happens on the web server, in languages such as PHP or Python. It is used for anything that needs the server's data or must be trusted: logging in, reading and writing the database, taking payments and building dynamic pages. The user never sees the server-side code, only the page it produces.
Common mistake: thinking client-side validation is enough to protect a website. The user controls their own browser, so they can switch off JavaScript or send data directly to the server without using the page at all. Client-side checks improve the experience, but the server must check every value again before trusting it.
Worked example 6: the cost of a round trip
A form has 5 fields. If each field were checked by the server, with a round trip of 120 ms each time, how long would the user wait in total? How long with JavaScript checking them in the browser?
| Working | Reason |
|---|---|
| Server-side: 5 × 120 = 600 ms of waiting | Every check needs a round trip |
| Client-side: almost no delay | The checks run on the user's own device |
| The server must still check once on submission | The browser's checks cannot be trusted |
| Total: one round trip of 120 ms instead of five | Client-side checks for speed, server-side for safety |
Worked example 7: choosing where code runs
A school's online booking system must show available parents' evening slots, check that a pupil number has six digits, and save each booking. Decide where each task should run.
| Working | Reason |
|---|---|
| Show available slots: server-side | The slots are stored in the server's database |
| Check six digits as they are typed: client-side | Instant feedback, with no server needed |
| Check the pupil number again on submission: server-side | Client checks can be bypassed |
| Save the booking: server-side | Only the server can write to the database |
Client-side code has limits. It depends on the user's device, so a slow phone runs it slowly. Its source can be read by anyone, so it must never contain secrets such as passwords. And it can be switched off. Server-side code keeps secrets safe and works the same for every user, but every request costs the server time and the user a round trip.
Modern web applications blur the line between the two. A mapping site, for example, runs a large JavaScript program in the browser that draws the map and responds to every drag and zoom. In the background, it keeps asking the server for the map tiles and search results it needs. The browser does the interactive work and the server supplies the data, which gives the speed of client-side code with the data of the server.
Check yourself. Why must a website check a form's data on the server even if JavaScript has already checked it?
Show the answer
The user controls the browser, so they can turn JavaScript off or send data straight to the server. Only checks on the server cannot be bypassed.
Section 5
Search engines and indexing
Crawling
A search engine starts by collecting pages. Programs called crawlers, or spiders, begin with a list of known pages and download each one. They find every link on it and add the linked pages to the list to visit. In this way they follow the links of the web outwards, visiting billions of pages and returning regularly to see what has changed.
Website owners can guide crawlers. A file called robots.txt asks crawlers to stay out of certain parts of a site, and a sitemap lists the pages the owner wants found. Pages that no other page links to may never be found at all.
The web changes constantly, so crawling never stops. Popular pages that change often, such as news sites, are revisited every few minutes, while quiet pages may be checked only every few weeks. Crawlers must also be polite: they limit how often they request pages from any one server, so as not to overload it with traffic.
Indexing
Searching billions of pages one by one for every query would be impossibly slow. Instead, the search engine builds an index in advance. An inverted index lists every word that appears anywhere, and for each word, the pages that contain it. It works like the index at the back of a textbook, which lists each topic and the pages where it appears.
To answer a query, the search engine looks up each word in the index and combines the lists. A query for an exact phrase, written in quotation marks, also checks that the words appear next to each other in the right order. It uses the positions stored in the index to do so. For a query of several words, it keeps the pages that appear in every list. Because the index is prepared in advance and stored for fast lookup, the answer takes a fraction of a second, however large the web.
The lists for each word are usually kept sorted by page number. Finding the pages common to two sorted lists then needs only one pass through each, like merging two sorted lists, rather than comparing every page with every other. For very common words the lists are enormous, which is one reason search engines often ignore words such as the and and.
Common mistake: thinking a search engine searches the whole web when you type a query. The web was crawled and indexed long before the query was typed. The search engine only looks words up in its index, which is why results arrive almost instantly, and why a brand-new page may not appear for a while.
Worked example 8: answering a query
Using the index above, which pages match the query coding club, and which match news dates?
| Working | Reason |
|---|---|
| coding: clubs, coding; club: clubs, coding | Look up each word |
| Both lists contain clubs and coding | Keep pages in every list |
| news: home, coding; dates: home, exams | Look up the second query's words |
| Only home is in both, so news dates matches home | The pages in common are the answer |
Worked example 9: the size of an index
A search engine indexes 4 billion pages with an average of 500 different words each. How many entries does its inverted index hold?
| Working | Reason |
|---|---|
| Entries = 4,000,000,000 × 500 | One entry for each word on each page |
| = 2,000,000,000,000 entries | That is two trillion entries |
| So the index is spread across thousands of servers | No single machine could hold it |
| A query still reads only a few short lists | Lookups stay fast however large the index |
Indexes hold more than just which pages contain each word. They also record where on the page each word appears. A word in the title or a heading can then count for more than one in a footnote, and phrases can be matched in order. Search engines also allow for different forms of a word, so a search for club can find clubs.
Check yourself. Why might a page published five minutes ago not appear in search results yet?
Show the answer
A crawler has not yet visited and indexed it. Queries only search the index, so a page appears only after it has been crawled and added.
Section 6
PageRank
Ranking by links
A query can match millions of pages, so the order of the results matters enormously. PageRank, developed by the founders of Google, ranks pages by the links that point to them. The idea is that a link from one page to another is a vote of confidence. A vote from an important page is worth more than a vote from an obscure one.
Each page's rank is shared out equally among the pages it links to. So a page with many incoming links from important pages, which do not link to much else, gets a high rank. A page linked only from unimportant pages, or from pages that link to hundreds of others, gets a low one.
The formula
The PageRank of a page A is worked out from the ranks of the pages T that link to it. Each is divided by the number of links C(T) going out of that page.
The damping factor d, usually 0.85, models a person clicking links at random who sometimes gets bored and jumps to a random page instead. Every page gets at least 1 − d = 0.15, even with no incoming links at all.
The random surfer gives an intuition for the whole calculation. Imagine someone who starts on a random page and keeps clicking a random link, but now and then jumps to a completely random page instead. Over a very long time, the share of their visits that land on each page is that page's rank. Pages that many paths lead to, especially from other popular pages, are visited most.
The formula refers to the ranks it is trying to find, so it is solved by iteration. Every page starts with a rank of 1. Each iteration works out every page's new rank from the old ranks, and the iterations are repeated until the ranks stop changing.
Figure 12.2 runs PageRank on four pages. Step through the iterations and watch the ranks settle. Then switch on the wrong model.
PageRank
- PR(A)
- 1.163
- PR(B)
- 1.036
- PR(C)
- 1.652
- PR(D)
- 0.150
Common mistake: thinking a page's rank is just how many pages link to it. PageRank weights each link by the rank of the page it comes from, shared among that page's links. A and B each have one incoming link, but A's comes from the top page, C, so A ranks well above B.
Worked example 10: one iteration
Pages A, B, C and D start with rank 1. A links to B and C; B links to C; C links to A; D links to C. Find the ranks after one iteration, with d = 0.85.
| Working | Reason |
|---|---|
| PR(A) = 0.15 + 0.85 × (1 ÷ 1) = 1 | Only C links to A, and C has one link |
| PR(B) = 0.15 + 0.85 × (1 ÷ 2) = 0.575 | A links to B, sharing its rank between two links |
| PR(C) = 0.15 + 0.85 × (1 ÷ 2 + 1 ÷ 1 + 1 ÷ 1) = 2.275 | A, B and D all link to C |
| PR(D) = 0.15 + 0.85 × 0 = 0.15 | No page links to D |
Worked example 11: the settled ranks
After many iterations the ranks settle at about A 1.49, B 0.783, C 1.577 and D 0.15. Explain the order.
| Working | Reason |
|---|---|
| C ranks highest, with three incoming links | It collects rank from A, B and D |
| A ranks second, though it has only one incoming link | That link comes from C, the top page, which links nowhere else |
| B ranks third with one link from A | A shares its rank between two links |
| D ranks last at 0.15 | Nothing links to D |
Derivation: why the ranks settle
Write the ranks of all n pages as a list r. One iteration replaces every rank using the old ones, which can be written as
where M shares each page's rank among its outgoing links. Each iteration shrinks any difference between two lists of ranks by a factor of d, so after k iterations an error has shrunk to
With d = 0.85, twenty iterations shrink the error to 0.85²⁰ ≈ 0.04 of its starting size, which is why a few dozen iterations are enough in practice.
Worked example 12: a three-page web
Pages P, Q and R start with rank 1. P links to Q; Q links to P and R; R links to P. Find the ranks after one iteration.
| Working | Reason |
|---|---|
| PR(P) = 0.15 + 0.85 × (1 ÷ 2 + 1 ÷ 1) = 1.425 | Q and R link to P; Q has two links |
| PR(Q) = 0.15 + 0.85 × (1 ÷ 1) = 1 | Only P links to Q, and P has one link |
| PR(R) = 0.15 + 0.85 × (1 ÷ 2) = 0.575 | Q shares its rank with R and P |
| P is ahead after one iteration | It has links from both other pages |
Real search engines combine PageRank with hundreds of other signals. These include how well the words of the query match the page, how recently it was updated and how quickly it loads. People also try to cheat the ranking, for example by creating many pages that link to each other. Search engines treat such link farms as spam and lower their rank.
PageRank's idea reaches far beyond web search. The same calculation can rank the importance of scientific papers from the papers that cite them, or of people in a social network from who follows whom. Whenever importance flows along links, a page, paper or person is important if important ones point to it, and iterating the shares until they settle finds out who.
Check yourself. Explain why a page with no incoming links still has a PageRank of 0.15.
Show the answer
The formula always adds 1 − d. With d = 0.85 that is 0.15, which models a random surfer jumping to any page at all, so every page has a small chance of being visited.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| HTTP and HTTPS | Requests and responses for the web | GET, POST, 200, 404 | One round trip per request |
| URL | Protocol, domain and path | https://…/clubs/chess.html | Query strings after ? |
| HTML | Content and structure as elements | h1, p, ul, a, img, div, form | A tree of elements |
| CSS selectors | Element, .class and #id | .notice, #main-title | External sheets restyle a whole site |
| Specificity | (ids, classes, elements) | div.card p is (0, 1, 2) | Compare left to right; ties go to the later rule |
| JavaScript | Behaviour in the browser | Form checks, DOM changes | Can be switched off |
| Client-side and server-side | Where processing runs | Validation; database access | Always recheck on the server |
| Crawler | Follows links to find pages | robots.txt, sitemaps | Unlinked pages may be missed |
| Inverted index | Each word and its pages | club: clubs, coding | Query = pages in every list |
| PageRank | Rank shared along links | PR(A) = (1 − d) + d Σ PR(T) ÷ C(T) | Iterate until settled; d = 0.85 |
Programming task
Programming task: a tiny search engine
Aim
Write a Python program that builds an inverted index for a small set of pages and answers queries of one or more words. It must rank the matching pages by PageRank, calculated from the links between them.
Design
The pages are a dictionary mapping each page's name to its text, and the links a dictionary mapping each page to the pages it links to. Building the index means splitting each page's text into lower-case words and adding the page to each word's list. A query keeps the pages that appear in the list of every query word.
PageRank starts every page at 1 and runs a fixed number of iterations. In each one, every page's new rank is 0.15 plus 0.85 times the sum, over the pages linking to it, of their rank divided by their number of links. All the new ranks are worked out from the old ones before any is replaced. The matches are then sorted by rank, highest first.
Code
pages = {
"home": "school news and term dates",
"clubs": "chess club and coding club times",
"exams": "exam dates and revision tips",
"coding": "coding club news",
}
links = {"home": ["clubs", "exams"], "clubs": ["coding"], "exams": ["home"], "coding": ["clubs"]}
index = {}
for name, text in pages.items():
for word in set(text.lower().split()):
index.setdefault(word, []).append(name)
def page_rank(links, d=0.85, iterations=20):
rank = {p: 1.0 for p in links}
for _ in range(iterations):
new = {}
for p in links:
incoming = [q for q in links if p in links[q]]
new[p] = (1 - d) + d * sum(rank[q] / len(links[q]) for q in incoming)
rank = new
return rank
def search(query):
words = query.lower().split()
matches = [p for p in pages if all(p in index.get(w, []) for w in words)]
rank = page_rank(links)
return sorted(matches, key=lambda p: -rank[p])
print(search("club"))
print(search("dates"))
Making a new dictionary of ranks in each iteration means every page is updated from the same old ranks, which matches the formula. The index uses a set of each page's words, so a page appears only once in a word's list however many times the word appears.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | search("club") | clubs, coding | Both pages contain club |
| 2 | search("coding club") | clubs, coding | Both pages contain both words |
| 3 | search("news dates") | home | Matches worked example 8 |
| 4 | search("dinosaur") | an empty list | A word in no page |
| 5 | PageRank of A, B, C, D after one iteration | 1, 0.575, 2.275, 0.15 | Matches worked example 10 |
| 6 | PageRank of A, B, C, D after 20 iterations | about 1.49, 0.783, 1.577, 0.15 | Matches worked example 11 |
| 7 | PageRank of P, Q, R after one iteration | 1.425, 1, 0.575 | Matches worked example 12 |
Evaluation
The search engine finds the right pages for every query and the PageRank function reproduces the worked examples, including the settled ranks in test 6. Ranking the matches by PageRank puts the better-linked page first when several pages match.
The program treats every word equally and ignores word order, so a page that mentions club once in passing ranks the same as one about clubs. An improvement would score each match by how often and where the query words appear, and combine that score with PageRank. It would also remove very common words, such as and, from the index.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State the job of each of HTML, CSS and JavaScript in a web page.
Worked solution to Q1
HTML describes the content of the page and its structure, such as headings and paragraphs. CSS describes how that content looks, such as colours and layout, and JavaScript adds behaviour, such as checking a form.
Q2. Describe what a web crawler does.
Worked solution to Q2
A crawler downloads a page, finds all the links on it and adds the linked pages to its list of pages to visit. Repeating this, it follows links across the web, and the pages it collects are then indexed.
Q3. Explain what the status codes 200 and 404 mean.
Worked solution to Q3
Status code 200 means the request succeeded and the content is included in the response. Status code 404 means the server could not find the page that was requested, for example because a link is out of date.
Rung 2: Application
Q4. Find the specificity of #menu .item a.
Worked solution to Q4
The selector contains one id, #menu, one class, .item, and one element, a. So its specificity is (1, 1, 1), which beats any selector without an id.
Q5. A page uses 2 style sheets, 3 scripts and 7 images. How many requests are needed, and how long do they take one after another at 50 ms each?
Worked solution to Q5
The page needs one request for the HTML plus one for each file: 1 + 2 + 3 + 7 = 13 requests. Made one after another, they take 13 × 50 = 650 ms.
Q6. Using the inverted index of section 5, which pages match the query dates?
Worked solution to Q6
Looking up dates in the index gives the list home and exams. A single-word query keeps every page in that list, so both pages match.
Q7. In the three-page web of worked example 12, find PR(Q) after one iteration, and explain why it is lower than PR(P).
Worked solution to Q7
Only P links to Q, and P has one link, so PR(Q) = 0.15 + 0.85 × 1 = 1. P has links from both Q and R, so it collects more rank: 1.425.
Rung 3: Analysis
Q8. Two rules apply to a paragraph: #intro p { color: red } and, later, div.box.wide p { color: blue }. What colour is it? Explain.
Worked solution to Q8
The first rule has specificity (1, 0, 1) and the second (0, 2, 2). The id counts are compared first, and 1 beats 0, so the paragraph is red even though the blue rule comes later.
Q9. A shop checks discount codes only with JavaScript. Explain why this is unsafe, and what it should do.
Worked solution to Q9
A customer can switch off JavaScript or send a request straight to the server, so any code would be accepted. The server must check every discount code itself before applying it, using its own list of valid codes.
Q10. Explain why a search engine builds an inverted index rather than reading pages when a query arrives.
Worked solution to Q10
Reading billions of pages for every query would take far too long. The inverted index is built in advance, so answering a query only means looking up a few words and combining their lists of pages.
Q11. In the four-page web, explain why A ends with a higher rank than B, though each has one incoming link.
Worked solution to Q11
A's link comes from C, the highest-ranked page, and C has only one outgoing link, so A gets all of C's share. B's link comes from A, which splits its rank between B and C.
Rung 4: Stretch
Q12. With d = 0.85, how many iterations shrink an error to below 1% of its starting size? Use the derivation.
Worked solution to Q12
The error shrinks by a factor of 0.85 each iteration, so we need 0.85ᵏ < 0.01. Taking logarithms gives k > log 0.01 ÷ log 0.85 ≈ 28.3, so 29 iterations are enough.
Q13. Explain why keeping content in HTML and appearance in CSS helps both disabled users and website designers.
Worked solution to Q13
Screen readers can read the HTML's structure directly, with headings and lists marked properly, whatever the styling. Designers can restyle the whole site by editing one style sheet, without touching any of the content.
Q14. A link farm of 1,000 pages all link to one page. Explain why this raises its PageRank less than it might seem, and how search engines respond.
Worked solution to Q14
Each farm page has almost no incoming links, so its own rank is only about 0.15, and it passes on just 0.85 × 0.15 of rank. Search engines also detect such networks of unimportant pages and treat their links as spam, reducing the target's rank.
Exam practice
Exam technique and worked answer workshop
When writing HTML, open and close every element in the right order, and give images alt text. When writing CSS, give the selector, then the property and value in curly brackets, and use a full stop for a class and a hash for an id.
For specificity questions, write the triple for each selector, compare ids, then classes, then elements, and only use the order if all three are equal. Always say why the winning rule wins.
For PageRank, write out the formula for each page, listing the pages that link to it and how many links each of those has. Use the old ranks for every page in an iteration, and give answers to three decimal places.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
(a) State the difference between the internet and the World Wide Web. [2]
(b) Describe what happens when a browser requests a web page. [2]
Mark scheme for exam question 1
- B1 the internet is the worldwide network of networks that carries data
- B1 the web is a service that runs on it, made of linked pages reached with HTTP
- B1 the browser finds the server's IP address using DNS and sends an HTTP GET request
- B1 the server responds with a status code and the page, which the browser displays
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
Write HTML for a page with the title Chess club and a top-level heading Chess club. Below the heading, add a paragraph saying We meet on Thursdays, and a link with the text All clubs to clubs.html.
Mark scheme for exam question 2
- B1 html, head and body elements in the right structure
- B1 a title element containing Chess club inside the head
- B1 an h1 element containing Chess club inside the body
- B1 a p element containing We meet on Thursdays
- B1 an a element with href="clubs.html" and the text All clubs
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
A style sheet contains div.card p { color: teal } followed by .card p { color: orange }.
(a) Give the specificity of each selector. [2]
(b) State the colour of a paragraph inside a div with the class card, and explain why. [2]
(c) State how the answer would change if the first selector were div p. [1]
Mark scheme for exam question 3
- B1 div.card p is (0, 1, 2)
- B1 .card p is (0, 1, 1)
- B1 teal
- B1 both have one class, but the first has more element selectors, so it is more specific; order only breaks ties
- B1 div p is (0, 0, 2), less specific than .card p, so the paragraph would be orange
Exam question 4 (5 marks · Paper 01 · about 7 minutes)
Pages A, B, C and D start with a PageRank of 1. A links to B and C; B links to C; C links to A; D links to C. The damping factor is 0.85.
(a) Calculate PR(C) after one iteration. [3]
(b) Explain why PR(D) is 0.15 after every iteration. [2]
Mark scheme for exam question 4
- M1 C is linked from A, with 2 links, and from B and D, each with 1
- M1 0.15 + 0.85 × (1 ÷ 2 + 1 + 1)
- A1 2.275
- B1 no page links to D, so the sum is zero
- B1 so PR(D) = 1 − 0.85 = 0.15
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A college is building a website where students book appointments with careers advisers. Discuss which processing should be done on the client and which on the server.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion of client-side and server-side processing, linked to the booking system. It covers speed, security, access to data and the need to validate on the server. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct description of both kinds of processing with some link to the website. The analysis is limited.
Level 1 (1–2 marks): some relevant points, such as that JavaScript runs in the browser, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- client-side JavaScript can check each field as it is typed, such as the format of a student number
- this gives instant feedback and avoids a round trip to the server for every mistake
- it also reduces the load on the college's server
- the available appointment times are stored in a database, so they must come from the server
- saving a booking must be done on the server, which alone can write to the database
- the server must check every value again, because client-side checks can be bypassed
- the server can stop two students booking the same slot, which the browser cannot know about
- login and personal data must be handled on the server, where secrets are kept safe
- conclusion: client-side for convenience and speed, server-side for data and anything that must be trusted
Annotated model answer: exam question 5
"JavaScript in the browser can check each field as the student types, such as making sure the student number has the right format. The student gets instant feedback, and the server is spared a request for every mistake." (Client-side, with two benefits.)
"The appointment times are stored in the college's database, so they must be sent by the server, and only the server can save a booking. It can also stop two students taking the same slot, which no single browser could know about." (Server-side for data, with a reason.)
"Because students control their own browsers, they could switch off JavaScript or send data directly. So the server must check every value again before saving it, and must handle logins and personal data itself." (Why server checks are essential.)
"So the college should use client-side processing for speed and convenience, and server-side processing for data and anything that must be trusted." (A justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It places each task where it belongs and explains why server-side checks can never be skipped.
Exam question 6 (4 marks · Paper 01 · about 5 minutes)
(a) Explain what an inverted index is. [2]
(b) Explain how it is used to answer a two-word query. [2]
Mark scheme for exam question 6
- B1 a list of every word found on the indexed pages
- B1 with, for each word, the pages that contain it
- B1 each word of the query is looked up to give a list of pages
- B1 the pages that appear in both lists are returned, then ranked
Exam question 7 (5 marks · Paper 01 · about 7 minutes)
Pages P, Q and R start with rank 1. P links to Q; Q links to P and R; R links to P. The damping factor is 0.85.
(a) Calculate PR(P) and PR(R) after one iteration. [4]
(b) State which page is ranked highest. [1]
Mark scheme for exam question 7
- M1 P is linked from Q, with 2 links, and R, with 1 link
- A1 PR(P) = 0.15 + 0.85 × 1.5 = 1.425
- M1 R is linked only from Q, with 2 links
- A1 PR(R) = 0.15 + 0.85 × 0.5 = 0.575
- B1 P
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
The pages' links are stored so that links[i] is a list of the pages that page i links to, for n pages. Write a function iterate(rank, links, n) that returns the new ranks after one PageRank iteration with d = 0.85.
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 a new array of n ranks, each starting at 0.15
- B1 a loop over every page q
- B1 a share of rank[q] ÷ the number of links from q worked out
- M1 0.85 × the share added to the new rank of every page that q links to
- A1 the new array returned, so that every page is updated from the old ranks
Annotated model answer: exam question 8
function iterate(rank, links, n)
array newRank[n]
for p = 0 to n - 1
newRank[p] = 0.15
next p
for q = 0 to n - 1
share = rank[q] / links[q].length
for each target in links[q]
newRank[target] = newRank[target] + 0.85 * share
next target
next q
return newRank
endfunction
Starting every new rank at 0.15 earns the second mark, and looping over every page earns the third. Working out each page's share earns the fourth, and adding 0.85 times the share to every page it links to earns the method mark. Returning a separate new array, so the old ranks are used throughout, earns the last. Sending each page's rank out along its links gives the same result as gathering it in, as the formula is written.
Connections
Synoptic link
Web pages travel by HTTP over the TCP/IP stack of Networks, protocols and the internet, and HTTPS uses the encryption of Compression, encryption and hashing. Server-side code reads and writes databases with the SQL of SQL and transaction processing.
The web is a directed graph, with pages as nodes and links as edges, so crawling is a graph traversal from Graph traversal and shortest paths. Client-side checks are the validation of Programming constructs, and the attacks they cannot stop, such as SQL injection, are covered in Network security and threats.
Synoptic question 1. A crawler follows links breadth first from a home page. Why does breadth-first crawling tend to find a site's important pages early?
Answer to synoptic question 1
Breadth-first search visits every page one link away before any page two links away. Important pages are usually linked directly from the home page, so they are reached in the first few steps.
Recap
Recap and next step
- The web runs on the internet; browsers send HTTP requests and servers reply with status codes and content. A URL gives the protocol, domain and path.
- HTML describes content and structure as a tree of elements, with attributes such as href, src, alt, class and id.
- CSS rules use element, class and id selectors; specificity (ids, classes, elements) decides between rules, and order only breaks ties.
- JavaScript adds behaviour in the browser; client-side processing is fast, but the server must handle data and recheck every value.
- Crawlers follow links, and an inverted index maps each word to its pages, so a query only combines lists.
- PageRank shares each page's rank along its links: PR(A) = (1 − d) + d Σ PR(T) ÷ C(T), iterated until it settles.
Next chapter: Number systems and binary arithmetic looks at how computers represent numbers in binary, the foundation for addresses, colours and every value a web page sends.
For your exam board
OCR A Level Computer Science (H446): this chapter covers section 1.3.4, Web Technologies, in Component 01: HTML, CSS and JavaScript, search engine indexing, the PageRank algorithm, and server-side and client-side processing.
AQA A Level Computer Science (7517): the World Wide Web, URLs and the client–server model appear in the fundamentals of communication and networking section, assessed on Paper 2. HTML, CSS and PageRank go beyond the required content but support the networking topics.