Similar to How to deal with single quote in xpath, I want to escape single quotes. The difference is that I can\'t exclude the possibility that a double quote might also app
I added the cat
function to the target inside the html_nodes()
function call. Seems to handle both the cases. cat()
also has the side-effect of printing the escaped text.
library(rvest)
library(magrittr)
html <- "1Father's son"
target <- "Father's son"
html %>% xml2::read_html() %>% html_nodes(xpath = paste0("//*[contains(text(), \"",cat(target),"\")]"))
#> Father's son
#> {xml_nodeset (4)}
#> [1] \n1\nFather's son\n
#> [2] \n1\nFather's son\n
#> [3] 1\n
#> [4] Father's son
html <- "1Father said \"Hello!\""
target <- 'Father said "Hello!"'
html %>% xml2::read_html() %>% html_nodes(xpath = paste0("//*[contains(text(), \"",cat(target),"\")]"))
#> Father said "Hello!"
#> {xml_nodeset (4)}
#> [1] \n1\nFather said "Hello!"\n ...
#> [2] \n1\nFather said "Hello!"\n
#> [3] 1\n
#> [4] Father said "Hello!"