我对使用rvest抓取一些数据很感兴趣,并使用以下教程作为指导:
https://statsandr.com/blog/web-scraping-in-r/
我知道如何在html浏览器中找到正确的表,并复制了该表,如教程所示。
library(rvest)
link <- "https://en.wikipedia.org/wiki/List_of_Formula_One_drivers"
page <- read_html(link)
# scrape F1 driver table
drivers_F1 <- html_element(page, "table.sortable") %>%
html_table()
字符串
从我所知道的来看,这两个表都有相同的选择器。我如何找到正确的选择器来使用html_element()为这个wiki页面上的下表(“List of Formula One drivers by country”)生成一个表?
Chrome html source的
html_element()是否默认选择匹配选择器的第一个示例?当使用html_selectors()时,我可以查看这两个表:
html_elements(page, "table.sortable")
{xml_nodeset (2)}
[1] <table class="wikitable sortable" style="font-size: 85%; text-align:center">\n<caption>Formula One drivers by name\n</caption>\n<tbody>\n<tr> ...
[2] <table class="wikitable sortable" style="text-align:center; text-align:center; font-size:95%">\n<caption>List of Formula One drivers by count ...
型
此外,如果使用html_elements()函数,则可以通过选择第二个索引元素来生成第二个表。
html_elements(page, "table.sortable")[[2]]%>%
html_table()
# A tibble: 42 × 7
Country Totaldrivers Champions Championships `Race wins` `First driver(s)` Most recent driver(s…¹
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 Argentinadetails 25 1(Fangio [5]) 5(1951, 1954, 1955, … "38\n(Fang… Juan Manuel Fang… Gastón Mazzacane(2001…
2 Australiadetails 18 2(Brabham [3], Jones) 4(1959, 1960, 1966, … "43\n(Brab… Tony Gaze(1952 B… Oscar Piastri, Daniel…
3 Austriadetails 16 2(Rindt, Lauda [3]) 4(1970, 1975, 1977, … "41\n(Rind… Jochen Rindt(196… Christian Klien(2010 …
4 Belgiumdetails 24 0 0 "11\n(Ickx… Johnny Claes(195… Stoffel Vandoorne(201…
5 Brazildetails 32 3(Fittipaldi [2], Piquet [3], Senna [3]) 8(1972, 1974, 1981, … "101\n(Fit… Chico Landi(1951… Pietro Fittipaldi(202…
6 Canadadetails 15 1(J. Villeneuve) 1(1997) "17\n(G. V… Peter Ryan(1961 … Lance Stroll(2023 Abu…
7 Chile 1 0 0 "0" Eliseo Salazar(1… Eliseo Salazar(1983 B…
8 China 1 0 0 "0" Zhou Guanyu(2022… Zhou Guanyu(2023 Abu …
9 Colombiadetails 3 0 0 "7\n(Monto… Ricardo Londoño(… Juan Pablo Montoya(20…
10 Czech Republic 1 0 0 "0" Tomáš Enge(2001 … Tomáš Enge(2001 Japan…
# ℹ 32 more rows
# ℹ abbreviated name: ¹`Most recent driver(s)/Current driver(s)`
# ℹ Use `print(n = ...)` to see more rows
型
在这种情况下,使用html_elements()似乎可以很好地完成工作,但是如果您能深入了解html_element()为什么会以这种方式工作,我们将不胜感激。
1条答案
按热度按时间dgtucam11#
html_elements
返回所有匹配项的列表,而html_element
返回与输入长度相同的节点集
即,在多个匹配的情况下,包含第一匹配的节点集。
除了使用
html_elements
,然后从返回的列表中选择所需的元素之外,您还可以通过更具体的方式使用html_element
来获得第二个表,例如使用伪类:last-of-type
,您可以选择最后一个表,或者使用:caption
,您可以根据文本进行选择,例如表标题:字符串