Modifying empty fields
You can access and modify a field with an empty name directly by using the field's index, for example like this:
pgform$fields[[2]]$value <- 'Paris'
If you want to find the index of the field dynamically by its type, you could do that like this:
for (i in 1:length(pgform$fields))
if (is.null(pgform$fields[[i]]$name) && pgform$fields[[i]]$type == 'text')
pgform$fields[[i]]$value <- 'Paris'
Your specific problem
For your specific website, the above will not give you the expected results. The field you need to modify to submit a query is q
, so you would want to do something like this:
session <- html_session('https://www.tripadvisor.com/')
pgform <- html_form(session)[[1]]
pgform <- set_values(pgform, q = 'Paris')
result <- submit_form(session, pgform)
This will load the desired page for you but will not provide you with the content you are probably looking for, as that content would only be loaded dynamically by the browser using a XMLHttpRequest
. To also get the content you would instead need to do something like this:
session <- html_session('https://www.tripadvisor.com/')
pgform <- html_form(session)[[1]]
pgform <- set_values(pgform, q = 'Paris')
result <- submit_form(session, pgform, submit = NULL, httr::add_headers('x-requested-with' = 'XMLHttpRequest'))
That will give you the content without the surrounding page structure.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…