-
Notifications
You must be signed in to change notification settings - Fork 0
/
session900.html
723 lines (646 loc) · 35.8 KB
/
session900.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Session 9</title>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/simple.css" id="theme">
<!-- Custom css -->
<link rel="stylesheet" href="css/custom.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<a href="index.html"><img border="0" alt="Courses" src="imgs/logo.png"></a>
<div class="reveal">
<div class="slides">
<section>
<h2>Introduction to programming using Python</h2>
<h3>Session 9</h3>
<p>Matthieu Choplin</p>
<p><a href='mailto:matthieu.choplin@city.ac.uk'>matthieu.choplin@city.ac.uk</a></p>
<p><a href='http://moodle.city.ac.uk/'>http://moodle.city.ac.uk/</a></p>
</section>
<section>
<h3>Objectives</h3>
<ul style="width:100%;font-size: 28px">
<li>Quick review of what HTML is</li>
<li>The find() string method</li>
<li>Regular expressions</li>
<li>Installing external libraries</li>
<li>Using a web parser: BeautifulSoup</li>
<li>Submitting data to a form using MechanicalSoup</li>
<li>Fetching data in real time</li>
</ul>
</section>
<section>
<h3>The HTML language</h3>
<ul>
<li>The primary language of information on the internet is the HTML</li>
<li>Every webpages are written in HTML</li>
<li>To see the source code of the webpage you are currently seeing,
do either right click and select "View page Source".
Or from the top menu of your browser, click on View and "View Source".</li>
</ul>
</section>
<section>
<h3>Example</h3>
<p><a target="_blank" href="http://mattchoplin.com/python_city/practice/Profile_Aphrodite.htm">Profile_Aphrodite.htm</a></p>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 26px;"><html><head><meta http-equiv="Content-Type"
content="text/html; charset=windows-1252">
<title>Profile: Aphrodite</title>
<link rel="stylesheet" type="text/css"></head>
<body bgcolor="yellow">
<center>
<br><br>
<img src="./Profile_ Aphrodite_files/aphrodite.gif">
<h2>Name: Aphrodite</h2>
<br><br>
Favorite animal: Dove
<br><br>
Favorite color: Red
<br><br>
Hometown: Mount Olympus
</center>
</body></html></code></pre></div>
</section>
<section>
<h3>Grab all html from a web page</h3>
<div><pre class="solution-content python"><code>from urllib.request import urlopen
my_address = "http://mattchoplin.com/python_city/practice/Profile_Aphrodite.htm"
html_page = urlopen(my_address)
html_text = html_page.read().decode('utf-8')
print(html_text)</code></pre></div>
<p>What is the type of object that is returned?</p>
</section>
<section>
<h3>Parsing a web page with a String's method</h3>
<ul>
<li>You can use the <strong>find()</strong> method</li>
<li>Example:</li>
</ul>
<iframe src="https://trinket.io/embed/python/48fb22f2f5" width="100%" height="300" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
<!--
<div><pre class="solution-content python"><code>this_is_my_string = 'Programming in python'
string_to_find = input('Enter a string to find in \'%s\': ' % this_is_my_string)
index_found = this_is_my_string.find(string_to_find)
print(index_found)
print(this_is_my_string[index_found])</code></pre></div>
-->
</section>
<section>
<h3>Find a word between 2 other words</h3>
<iframe src="https://trinket.io/embed/python/b7f28ac6c1" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
<!--
<div><pre class="solution-content python"><code>my_string = 'some text with a special word ' \
'<strong>Equanimity</strong>'
start_tag = "<strong>"
end_tag = "</strong>"
start_index = my_string.find(start_tag) + len(start_tag)
end_index = my_string.find(end_tag)
# We extract the text between
# the last index of the first tag '>'
# and the first index of the second tag '<'
print(my_string[start_index:end_index])</code></pre></div>
-->
</section>
<section>
<h3>Parsing the title with the find() method</h3>
<div><pre class="solution-content python"><code>from urllib.request import urlopen
my_address = "http://mattchoplin.com/python_city/" \
"practice/Profile_Aphrodite.htm"
html_page = urlopen(my_address)
html_text = html_page.read().decode('utf-8')
start_tag = "<title>"
end_tag = "</title>"
start_index = html_text.find(start_tag) + len(start_tag)
end_index = html_text.find(end_tag)
print(html_text[start_index:end_index])</code></pre></div>
</section>
<section>
<h3>Limitation of the find() method</h3>
<ul>
<li>Try to use the same script for extracting the title of <a target="_blank" href="http://mattchoplin.com/python_city/practice/Profile_Poseidon.htm">Profile_Poseidon.htm</a> </li>
</ul>
<div><pre class="solution-content python"><code>from urllib.request import urlopen
my_address = "http://mattchoplin.com/python_city/" \
"practice/Profile_Poseidon.htm"
html_page = urlopen(my_address)
html_text = html_page.read().decode('utf-8')
start_tag = "<title>"
end_tag = "</title>"
start_index = html_text.find(start_tag) + len(start_tag)
end_index = html_text.find(end_tag)
print(html_text[start_index:end_index])</code></pre></div>
</section>
<section>
<h3>Limitation of the find() method</h3>
<ul>
<li>Do you see the difference? We are not getting what we want now:</li>
</ul>
<div><pre class="solution-content python"><code><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title >Profile: Poseidon</code></pre></div>
<ul>
<li>This is because of the extra space before the closing ">" in <title ></li>
<li>The html is still rendered by the browser, but we cannot rely on it completely if we want to parse a web page </li>
</ul>
</section>
<section>
<h3>Regular expressions</h3>
<ul>
<li>They are used to determine whether or not a text matches a particular pattern</li>
<li>We can use them thanks to the <strong>re</strong> module in python</li>
<li>They use special characters to represent patterns: ^, $, *, +, ., etc...</li>
</ul>
</section>
<section>
<h3>re.findall() using *</h3>
<ul>
<li>The asterisk character <strong>*</strong> stands for "zero or more" of whatever came just before the asterisk</li>
<li><strong>re.findall():</strong></li>
<ul>
<li>finds any text within a string that matches a given pattern i.e. regex</li>
<li>takes 2 arguments, the 1st is the regex, the 2nd is the string to test</li>
<li>returns a list of all matches</li>
</ul>
</ul>
<p></p>
<div><pre class="solution-content python"><code># re.findall(<regular_expression>, <string_to_test>)</code></pre></div>
</section>
<section>
<h3>Interactive example</h3>
<iframe src="https://trinket.io/embed/python/7c42a37566" width="100%" height="450" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
</section>
<section>
<h3>re.findall() case insensitive</h3>
<ul>
<li>Note that re.findall() is case sensitive</li>
<div><pre class="solution-content python"><code>re.findall('ab*c', 'ABC') # nothing found</code></pre></div>
<li>We can use a 3rd argument <strong>re.IGNORECASE</strong> to ignore the case</li>
<div><pre class="solution-content python"><code>re.findall('ab*c', 'ABC', re.IGNORECASE) # ABC found</code></pre></div>
</ul>
</section>
<section>
<h3>re.findall() using . (period)</h3>
<ul>
<li>the period <strong>.</strong> stands for any single character in a regular expression</li>
<li>for instance we could find all the strings that contains the letters "a" and "c" separated by a single character as follows:</li>
<iframe src="https://trinket.io/embed/python/396b754ffd" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
</ul>
</section>
<section>
<h3>re.findall() using .* (period asterisk)</h3>
<ul>
<li>the term <strong>.*</strong> stands for any character being repeated any number of times</li>
<li>for instance we could find all the string that starts with "a" and ends with "c", regardless of what is in between with:</li>
<iframe src="https://trinket.io/embed/python/1bae467299" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
</ul>
<!--
import re
print(re.findall('a.*c', 'abc'))
print(re.findall('a.*c', 'abbc'))
print(re.findall('a.*c', 'ac'))
print(re.findall('a.*c', 'acc'))
-->
</section>
<section>
<h3>re.search()</h3>
<ul>
<li><strong>re.search():</strong></li>
<ul>
<li>searches for a particular pattern inside a string</li>
<li>returns a MatchObject that stores different "groups" of data</li>
<li>when we call the group() method on a MatchObject, we get the first and most inclusive result</li>
</ul>
</ul>
<div><pre class="solution-content python"><code>import re
match_results = re.search('ab*c', 'ABC', re.IGNORECASE)
print(match_results.group()) # returns ABC</code></pre></div>
</section>
<section>
<h3>re.sub()</h3>
<ul>
<li>re.sub()</li>
<ul>
<li>allows to replace a text in a string that matches a pattern with a substitute (like the replace() string method)</li>
<li>takes 3 arguments:</li>
<ol>
<li>regex</li>
<li>replacement text</li>
<li>string to parse</li>
</ol>
</ul>
</ul>
<div><pre class="solution-content python"><code>my_string = "This is very boring"
print(my_string.replace('boring', 'funny'))
import re
print(re.sub('boring', 'WHAT?', my_string))</code></pre></div>
</section>
<section>
<h3>greedy regex (*)</h3>
<ul>
<li><strong>greedy</strong> expressions try to find the longest possible match when character like <strong>*</strong> are used</li>
<li>for instance, in this example the regex finds everything between '<' and '>' which is actually the whole <em>'<replaced> if it is in <tags>'</em></li>
</ul>
<div><pre class="solution-content python"><code>my_string = 'Everything is <replaced> if it is in <tags>'
my_string = re.sub('<.*>', 'BAR', my_string)
print(my_string) # 'Everything is BAR'</code></pre></div>
</section>
<section>
<h3>non-greedy regex (*?)</h3>
<ul>
<li><strong>*?</strong></li>
<ul>
<li>works the same as * BUT matches the shortest possible string of text</li>
</ul>
</ul>
<div><pre class="solution-content python"><code>my_string = 'Everything is <replaced> if it is in <tags>'
my_string = re.sub('<.*?>', 'BAR', my_string)
print(my_string) # 'Everything is BAR if it is in BAR'</code></pre></div>
</section>
<section>
<h3>Use case: Using regex to parse a webpage</h3>
<ul>
<li><a target="_blank" href="http://mattchoplin.com/python_city/practice/Profile_Dionysus.htm">Profile_Dionysus.htm</a></li>
<li>We want to extract the title:</li>
<div><pre class="solution-content python"><code><TITLE >Profile: Dionysus</title / ></code></pre></div>
<li>We will use the regular expression for this case</li>
</ul>
</section>
<section>
<h3>Use case: solution</h3>
<div><pre class="solution-content python"><code>import re
from urllib.request import urlopen
my_address = "http://mattchoplin.com/python_city/practice/Profile_Dionysus.htm"
html_page = urlopen(my_address)
html_text = html_page.read().decode('utf-8')
match_results = re.search("<title .*?>.*</title .*?>", html_text, re.IGNORECASE)
title = match_results.group()
title = re.sub("<.*?>", "", title)
print(title)</code></pre></div>
</section>
<section>
<h3>Use case: explanation</h3>
<ul>
<li><title .*?> finds the opening tag where there must be a space after the word "title" and the tag must be closed,
but any characters can appear in the rest of the tag.
We use the non-greedy <strong>*?</strong>, because we want the first closing ">" to match the tag's end</li>
<li><strong>.*</strong> any character can appear in between the <title> tag</li>
<li><\title .*?> same expression as the first part but with the forward slash to represent a closing HTML tag</li>
<li>More on regex: <a target="_blank" href="https://docs.python.org/3.5/howto/regex.html">https://docs.python.org/3.5/howto/regex.html</a></li>
</ul>
</section>
<section id="installing-package">
<h3>Installing an external library</h3>
<ul>
<li>Sometimes what you need is not included in the python standard library and you have to install an external library</li>
<li>You are going to use a python package manager: <strong><a target="_blank" href="https://pip.pypa.io/en/latest/installing/">pip</a></strong></li>
<li>The packages (libraries) that you can install with pip are listed on <a target="_blank" href="https://pypi.python.org/pypi">https://pypi.python.org/pypi</a></li>
<li>If you do not have pip, you can use the command "python setup.py install" from the package you would have downloaded and uncompressed from <a target="_blank" href="https://pypi.python.org/pypi">pypi</a></li>
</ul>
</section>
<section>
<h3>Installing with Pycharm (1)</h3>
<img src="imgs/pycharm_install_package1.PNG" style="background:none; border:none; box-shadow:none; margin-top:0px;height: 450px"/>
</section>
<section>
<h3>Installing with Pycharm (2)</h3>
<img src="imgs/pycharm_install_package2.PNG" style="background:none; border:none; box-shadow:none; margin-top:0px;height: 450px"/>
</section>
<section>
<h3>Installing with Pycharm (3)</h3>
<img src="imgs/pycharm_install_package3.PNG" style="background:none; border:none; box-shadow:none; margin-top:0px;height: 450px"/>
</section>
<section>
<h3>Using Beautiful Soup</h3>
<div><pre class="solution-content python"><code>from bs4 import BeautifulSoup
from urllib.request import urlopen
my_address = "http://mattchoplin.com/python_city/" \
"practice/Profile_Dionysus.htm"
html_page = urlopen(my_address)
html_text = html_page.read().decode('utf-8')
my_soup = BeautifulSoup(html_text, "html.parser")</code></pre></div>
</section>
<section>
<h3>BeautifulSoup: get_text()</h3>
<ul>
<li><strong>get_text()</strong></li>
<ul>
<li>is extracting only the text from an html document</li>
<div><pre class="solution-content python"><code>print(my_soup.get_text())</code></pre></div>
</ul>
<li>there are lot of blank lines left but we can remove them with the method <strong>replace()</strong></li>
<div><pre class="solution-content python"><code>print(my_soup.get_text().replace("\n\n\n",""))</code></pre></div>
<li>Using BeautifulSoup to extract the text first and use the find() method is <em>sometimes</em> easier than to use regular expressions</li>
</ul>
</section>
<section>
<h3>BeautifulSoup: find_all()</h3>
<ul>
<li>find_all()</li>
<ul>
<li>returns a list of all elements of a particular tag given in argument</li>
</ul>
<div><pre class="solution-content python"><code>print(my_soup.find_all("img"))</code></pre></div>
<li>What if the HTML page is broken?</li>
</ul>
</section>
<section>
<h3>BeautifulSoup: Tags</h3>
<div><pre class="solution-content python"><code style="line-height: 100%">[<img src="dionysus.jpg"/>, <img src="grapes.png"><br><br>
Hometown: Mount Olympus
<br><br>
Favorite animal: Leopard <br>
<br>
Favorite Color: Wine
</br></br></br></br></br></br></img>]</code></pre></div>
<ul>
<li>This is not what we were looking for. The <img> is not properly closed therefore BeautifulSoup ends up adding a fair
amount of HTML after the image tag before inserting a </img> tag on its own. This can happen with real case.</li>
<li>NB: BeautifulSoup is storing HTML tags as <em>Tag</em> objects and we can extract information from each Tag.</li>
</ul>
</section>
<section>
<h3>BeautifulSoup: Extracting information from Tags</h3>
<ul>
<li><strong>Tags</strong>:</li>
<ul>
<li>have a name</li>
<li>have attributes, accessible using keys, like when we access values of a dictionary through its keys</li>
</ul>
</ul>
<div><pre class="solution-content python"><code>for tag in my_soup.find_all("img"):
print(tag.name)
print(tag['src'])</code></pre></div>
</section>
<section>
<h3>BeautifulSoup: accessing a Tag through its name</h3>
<ul>
<div><pre class="solution-content python"><code>print(my_soup.title)</code></pre></div>
<li>The HTML is cleaned up</li>
<li>We can use the string attributes stored by the title</li>
<div><pre class="solution-content python"><code>print(my_soup.title.string)</code></pre></div>
</ul>
</section>
<section>
<h3>The select method (1)</h3>
<ul>
<li>... will return a list of Tag objects, which is how Beautiful Soup represents an HTML element. The list will
contain one Tag object for every match in the BeautifulSoup object's HTML</li>
</ul>
</section>
<section id="beautifulsoup-select">
<h3>The select method (2)</h3>
<table style="font-size: 24px">
<tr>
<th style="width: 30%;">Selector passed to the select method</th>
<th>Will match...</th>
</tr>
<tr>
<td>soup.select('div')</td>
<td>All elements named <div></td>
</tr>
<tr>
<td>soup.select('#author')</td>
<td>The element with an <strong>id</strong> attribute of <strong>author</strong></td>
</tr>
<tr>
<td>soup.select('.notice')</td>
<td>All elements that use a CSS</td>
</tr>
<tr>
<td>soup.select('div span')</td>
<td>All elements named <span> that are within an element named <div></td>
</tr>
<tr>
<td>soup.select('div > span')</td>
<td>All elements named <span> that are directly within an element named <div>, with no other elements in between</td>
</tr>
<tr>
<td>soup.select('input[name]')</td>
<td>All elements named <input> that have a <strong>name</strong> attribute with any value</td>
</tr>
<tr>
<td>soup.select('input[type="button"]')</td>
<td>All elements named <input> that have an attribute name <strong>type</strong> with value <strong>button</strong></td>
</tr>
</table>
</section>
<section>
<h3>Emulating a web browser</h3>
<ul>
<li>Sometimes we need to submit information to a web page, like a login page</li>
<li>We need a web browser for that</li>
<li><strong><a target="_blank" href="https://github.com/hickford/MechanicalSoup">MechanicalSoup</a></strong> is an alternative to urllib that can do all the same things but has more added
functionality that will allow us to talk back to webpages without using a standalone browser,
perfect for fetching web pages, clicking on buttons and links, and filling out and submitting forms</li>
</ul>
</section>
<section>
<h3>Installing MechanicalSoup</h3>
<ul>
<li>You can install it with pip: <em>pip install MechanicalSoup</em> or within Pycharm (like what we did earlier with BeautifulSoup)</li>
<li>You might need to restart your IDE for MechanicalSoup to load and be recognised</li>
</ul>
</section>
<section>
<h3>MechanicalSoup: Opening a web page</h3>
<ul>
<li>Create a browser</li>
<li>Get a web page which is a Response object</li>
<li>Access the HTML content with the <em>soup</em> attribute</li>
<div><pre class="solution-content python"><code>import mechanicalsoup
my_browser = mechanicalsoup.Browser(
soup_config={'features':'html.parser'})
page = my_browser.get("http://mattchoplin.com/python_city/" \
"practice/Profile_Aphrodite.htm")
print(page.soup)</code></pre></div>
</ul>
</section>
<section>
<h3>MechanicalSoup: Submitting values to a form</h3>
<ul>
<li>Have a look at this <a target="_blank" href="https://whispering-reef-69172.herokuapp.com/login">login page</a></li>
<li>The important section is the login form</li>
<li>We can see that there is a submission <form> named "login" that includes two <input> tags, one named
<em>username</em> and the other one named <em>password</em>.</li>
<li>The third <input> is the actual "Submit" button</li>
</ul>
</section>
<section>
<h3>MechanicalSoup: script to login</h3>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 26px;">import mechanicalsoup
my_browser = mechanicalsoup.Browser(
soup_config={'features':'html.parser'})
login_page = my_browser.get(
"https://whispering-reef-69172.herokuapp.com/login")
login_html = login_page.soup
form = login_html.select("form")[0]
form.select("input")[0]["value"] = "admin"
form.select("input")[1]["value"] = "default"
profiles_page = my_browser.submit(form, login_page.url)
print(profiles_page.url)
print(profiles_page.soup)</code></pre></div>
</section>
<section>
<h3>Methods in MechanicalSoup</h3>
<ul>
<li>We created a Browser object</li>
<li>We called the method <em>get</em> on the Browser object to get a web page</li>
<li>We used the <em>select()</em> method to grab the form and input values in it</li>
</ul>
</section>
<section>
<h3>Interacting with the Web in Real Time</h3>
<ul>
<li>We want to get data from a website that is constantly updated</li>
<li>We actually want to simulate clicking on the "refresh" button</li>
<li>We can do that with the <em>get</em> method of MechanicalSoup</li>
</ul>
</section>
<section>
<h3>Use case: fetching the stock quote from Yahoo finance (1)</h3>
<ul>
<li>Let us identify what is needed</li>
<li>
<ul>
<li>What is the source of the data? <br/><strong><a href="https://www.bloomberg.com/quote/YHOO:US">https://www.bloomberg.com/quote/YHOO:US</a></strong></li>
<li>What do we want to extract from this source? <br/><strong>The stock price</strong></li>
</ul>
</li>
</ul>
</section>
<section>
<h3>Use case: fetching the stock quote from Yahoo finance (2)</h3>
<ul>
<li>If we look at the source code, we can see what the tag is for the stock and how to retrieve it:</li>
<li><div><pre class="solution-content python"><code style="line-height: 100%;font-size: 26px;"><div class="price">40.08</div></code></pre></div></li>
<li>We check that <div class="price"> only appears once in the webpage since
it will be a way to identify the location of the current price</li>
</ul>
</section>
<section>
<h3>MechanicalSoup: script to find Yahoo current price</h3>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 26px;">import mechanicalsoup
my_browser = mechanicalsoup.Browser()
page = my_browser.get("https://www.bloomberg.com/quote/YHOO:US")
html_text = page.soup
# return a list of all the tags where
# the css class is 'price'
my_tags = html_text.select(".price")
# take the BeautifulSoup string out of the
# first (and only) <span> tag
my_price = my_tags[0].text
print("The current price of "
"YHOO is: {}".format(my_price))</code></pre></div>
</section>
<section>
<h3>Repeatedly get the Yahoo current price</h3>
<ul>
<li>Now that we know how to get the price of a stock from the Bloomberg web page, we can create a for loop to stay up to date</li>
<li>Note that we should not overload the Bloomberg website with more requests than we need. And also, we should also have a look at their
<a href="https://www.bloomberg.com/robots.txt">robots.txt</a> file to be sure that what we do is allowed
</li>
</ul>
</section>
<section>
<h3>Introduction to the <em>time.sleep()</em> method</h3>
<ul>
<li>The <em>sleep()</em> method of the module time takes a number of seconds as argument
and waits for this number of seconds, it enables to delay the execution of a statement in the program</li>
</ul>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 26px;">from time import sleep
print "I'm about to wait for five seconds..."
sleep(5)
print "Done waiting!"</code></pre></div>
</section>
<section>
<h3>Repeatedly get the Yahoo current price: script</h3>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 24px;">from time import sleep
import mechanicalsoup
my_browser = mechanicalsoup.Browser()
# obtain 1 stock quote per minute for the next 3 minutes
for i in range(0, 3):
page = my_browser.get("https://www.bloomberg.com/quote/YHOO:US")
html_text = page.soup
# return a list of all the tags where the class is 'price'
my_tags = html_text.select(".price")
# take the BeautifulSoup string out of the first tag
my_price = my_tags[0].text
print("The current price of YHOO is: {}".format(my_price))
if i<2: # wait a minute if this isn't the last request
sleep(60)</code></pre></div>
</section>
<section>
<h3>Exercise: putting it all together</h3>
<ul>
<li>Install a new library called <em>requests</em></li>
<li>Using <a href="#/beautifulsoup-select">the select method</a> of BeautifulSoup, parse (that
is, analyze and identify the parts of) the image of the day of <a href="http://xkcd.com/">http://xkcd.com/</a></li>
<li>Using the <em>get</em> method of the <em>requests</em> library, download the image</li>
<li>Complete the following program <a href="exercises/xkcd_incomplete.py">xkcd_incomplete.py</a></li>
</ul>
</section>
<section>
<h3>Using request</h3>
<ul>
<li>You first have to import it</li>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 24px;">import requests</code></pre></div>
<li>If you want to download the webpage, use the get() method with a url in parameter, such as:</li>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 24px;">res = requests.get(url)</code></pre></div>
<li>Stop your program if there is an error with the raise_for_status() method</li>
<div><pre class="solution-content python"><code style="line-height: 100%;font-size: 24px;">res.raise_for_status()</code></pre></div>
</ul>
</section>
<section>
<h3>Next? Web crawling!</h3>
<ul>
<li>From Wikipedia: A Web crawler is an Internet bot which systematically browses the World Wide Web, typically for the purpose of Web indexing.</li>
<li>How do you navigate a website? For example, for the <a href="http://xkcd.com/">http://xkcd.com/</a> website, how could you <strong>retrieve all of its images?</strong></li>
<li>Write down how you would design your program</li>
<li>Write the program</li>
</ul>
</section>
<section>
<h3>Solution fo Web Crawling</h3>
<div class="solution">
<p class="show-solution"><i class="fa fa-eye" aria-hidden="true"></i>Solution</p>
<p class="hide-solution" style="margin-top: 0px; margin-bottom: 0px;"><i class="fa fa-eye-slash" aria-hidden="true"></i>Hide solution</p>
<p class="solution-content python">Download the script here: <a href="exercises/xkcd_downloader.py">xkcd_downloader.py</a> </p>
</div>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
history: true,
slideNumber: true,
center: false,
// More info https://github.com/hakimel/reveal.js#dependencies
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/menu/menu.js' },
{ src: 'plugin/jquery-2.0.0.min.js' },
{ src: 'plugin/custom.js' },
{ src: 'plugin/clipboard.min.js' },
]
});
</script>
</body>
</html>