Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

How do I scrape HTML tables using the XML package?

Take, for example, this Wikipedia page on the Brazilian soccer team. I would like to read it in R and get the "list of all matches Brazil have played against FIFA recognized teams" table as a data.frame. How can I do this?

1 Answer

0 votes
by

To scrape HTML tables into R data frames using the XML package, you can use the following code:

library(XML)

library(RCurl)

library(rlist)

theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )

tables <- readHTMLTable(theurl)

tables <- list.clean(tables, fun = is.null, recursive = FALSE)

n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))

tables[[which.max(n.rows)]]

Output:

              V1  V2  V3  V4  V5   V6  V7    V8      V9

1        Opponent Pld   W   D   L   GF  GA    GD   Win %

2       Argentina 106  42  27  38  165 160    +5  39.62%

3        Paraguay  80  47  22  11  173  67  +106  58.75%

4         Uruguay  76  36  20  20  136  97   +39  47.36%

5           Chile  72  51  13   8  167  61  +106  70.08%

6            Peru  44  31   9   4   95  29   +66 +69.05%

7          Mexico  41  24   7  10   75  36   +41  58.53%

8         Ecuador  32  26   4   2   94  22   +72  82.75%

9         Bolivia  31  21   5   5   99  25   +74  67.74%

10       Colombia  31  19   9   3   62  15   +47  61.29%

11        England  26  11  11   4   34  23   +11  44.00%

12      Venezuela  25  21   3   1   89   8   +81  86.95%

13     Germany [note 2]  23  13   5   5   41  31   +10  56.52%

14       Portugal  20  13   3   4   39  16   +23  65.00%

15  United States  20  19   0   1   43  12   +31  95.00%

16   Serbia [note 3]  20  11   7   2   39  23   +16  55.00%

17 Czech Republic[note 4] 19  11   6   2   32  15   +17  57.89%

18          Italy  16   8   3   5   30  23    +7  50.00%

19         France  16   7   4   5   27  20    +7  43.75%

20         Sweden  15  10   3   2   35  17   +18  66.66%

21      Russia [note 5]  13   9   4   0   26   7   +19  69.23%

22         Poland  12   9   2   1   37  19   +18  75.00%

23    Netherlands  12   3   5   4   15  18    -3  25.00%

24          Japan  12  10   2   0   34   5   +29  81.81%

25     Costa Rica  11  10   0   1   34   9   +25  90.00%

26       Scotland  10   8   2   0   16   3   +13  80.00%

27          Wales  10   8   1   1   20   5   +15  80.00%

28        Austria  10   7   3   0   17   5   +12  70.00%

29          Spain   9   5   2   2   14   8    +6  55.55%

30    Switzerland   9   3   4   2   11   9    +2  33.30%

Related questions

Browse Categories

...