我想在應用如下過濾器后抓取http://csla.history.ox.ac.uk/search.php
- 點擊“圣”
- 在“出生/埋葬地區”下選擇“高盧和法蘭克王國”
- 點擊“應用搜索”
我很掙扎,因為 URL 沒有相應地更新。
原始碼<option value="Gaul">Gaul and Frankish kingdoms</option>如下
<div class="section colm colm6" id="fl-page4-12">
<label for="item_12"class="field-label">Region of Birth/Burial</label>
<label class="field select">
<select id="text-nine" name="form[item_89]">
<option value=""></option>
<option value="East">'The East' (unspecified)</option>
<option value="West">'The West' (unspecified)</option>
<option value="Britain">Britain and Ireland</option>
<option value="Gaul">Gaul and Frankish kingdoms</option>
然后,我想從所選網頁訪問以藍色書寫的 ID,即第一個將是E06478.
任何幫助將不勝感激!
uj5u.com熱心網友回復:
這是一個棘手的問題。您需要向POST服務器查詢,并且查詢需要采用非常特殊的格式。您可以像這樣從頁面中獲取 html:
library(httr)
library(rvest)
items <- c(998, 1, 18,89, 90, 2, 88, 20, 3, 4, 5, 6, 12, 13, 11, 999, 213, 214)
contents <- c('\nE\n', '\n\n', '\n\n', '\nGaul\n', rep('\n\n', 11), '\nOr\n',
'\n\n', '\n\n')
s <- paste0("-----------------------------39565121210000504382566389445\n",
"Content-Disposition: form-data; name=\"form[item_", items,
']\"\n', contents,
collapse = '')
s <- paste0(s, '-----------------------------39565121210000504382566389445--')
type <- paste0('multipart/form-data; boundary=---------------------------',
'39565121210000504382566389445')
res <- POST('http://csla.history.ox.ac.uk/results.php',
body = charToRaw(s),
content_type(type))
要在一個整潔的資料框中獲取所有結果,您可以執行以下操作:
df <- res %>%
read_html() %>%
html_elements(xpath = "//td[not(contains(@style, 'LightGray'))]") %>%
html_text() %>%
matrix(ncol = 2, byrow = TRUE) %>%
as.data.frame() %>%
setNames(c('ID', 'Title')) %>%
dplyr::as_tibble()
這將為您提供資料框中的所有參考 ID。要獲取實際頁面,我們使用這些作為查詢字串:
urls <- paste0("http://csla.history.ox.ac.uk/record.php?recid=", df$ID)
現在我們需要瀏覽所有 900 多個頁面來提取表格資料。在回圈中執行此操作然后在最后將串列系結在一起是最安全的:
all_results <- list()
for(i in seq_along(urls)) {
all_results[[i]] <- read_html(urls[i]) %>%
html_elements("td") %>%
html_text() %>%
matrix(ncol = 4, byrow = TRUE) %>%
as.data.frame() %>%
setNames(c("ID", "Name", "Name_in_source", "Identity"))
}
final_result <- dplyr::bind_rows(all_results)
最終結果現在是一個超過 3000 行的資料框。這是前3個:
head(final_result, 3)
#> ID Name Name_in_source Identity
#> 1 S01319 Orientius, bishop of Auch, 5th c. Certain
#> 2 S02351 Mamertus, bishop of Vienne (Gaul), ob. 475 Certain
#> 3 S00316 Martyrs of Lyon Certain
一些 ID 是重復的,因為它們出現在多個頁面中。您可以使用unique洗掉這些。另請注意,當您將資料框列印到控制臺時,希臘字母將顯示為 Unicode 轉義序列。文本仍然存在于底層向量中。例如:
head(final_result[3])
#> Name_in_source
#> 1
#> 2
#> 3
#> 4
#> 5 <U 03A0><U 03BF><U 03BB><U 03CD><U 03BA>a<U 03C1>p<U 03BF><U 03C2>
#> 6 <U 03A0><U 03B9><U 03CC><U 03BD><U 03B9><U 03BF><U 03C2>
但
final_result[1:6, 3]
#> [1] "" "" "" "" "Πολ?καρπο?" "Πι?νιο?"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490641.html
上一篇:如何在BeautifulSoup中從ul中提取li?
下一篇:使用R抓取在下一頁繼續的表
