Simultaneously escape double and single quotes in Xpath

前端 未结 4 950
梦谈多话
梦谈多话 2021-01-12 16:57

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

4条回答
  •  清酒与你
    2021-01-12 17:19

    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 <- "
    1
    Father'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] \n
    1
    \n
    Father's son
    \n #> [2] \n
    1
    \n
    Father's son
    \n #> [3]
    1
    \n #> [4]
    Father's son
    html <- "
    1
    Father 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] \n
    1
    \n
    Father said "Hello!"
    \n ... #> [2] \n
    1
    \n
    Father said "Hello!"
    \n #> [3]
    1
    \n #> [4]
    Father said "Hello!"

提交回复
热议问题