【问题标题】:How to scrape URL link from search box in R?如何从 R 中的搜索框中抓取 URL 链接?
【发布时间】:2019-10-28 15:27:50
【问题描述】:

我想从搜索框中获取输出的 URL 链接。 例如,如果我在https://www.realestate.co.nz/profile/ 的搜索框中输入“4/271 Balmoral Road”,它会显示相关结果并引导我转到https://www.realestate.co.nz/profile/0b27093b9ce641108f7a6033b9fdae28

所以在 R 中,如果我将“4/271 Balmoral Road”作为输入,我希望输出为“https://www.realestate.co.nz/profile/0b27093b9ce641108f7a6033b9fdae28

你能帮帮我吗?那将不胜感激。

我在下面的代码中使用了 Rvest,但没有用

'https://www.realestate.co.nz/profile?query=4/271%20Balmoral%20Road' %>%
  read_html() %>%
  html_nodes(xpath = '//*[@id="ember386"]/div[1]/div/a') %>% html_attr('href')

【问题讨论】:

    标签: r api web-scraping


    【解决方案1】:

    内容是动态检索的。您可以使用 httr 将地址查询发送到服务器,并使用 jsonlite 来处理来自服务器的 json 响应。您会在响应中获得 url 的“slugs”,您需要将其与最终 url 的基本字符串连接起来。


    R:

    library(httr)
    library(jsonlite)
    
    params = list('q' = '4/271 Balmoral Road')
    d <- jsonlite::parse_json(httr::GET(url = 'https://platform.realestate.co.nz/search/v1/suggest/property', query = params))
    base <- 'https://www.realestate.co.nz/profile/'
    print(paste0(base, d$data[[1]]$slug))
    

    或使用的版本 OP:

    library(httr) 
    library(jsonlite) 
    
    params = list('q' = '4/271 Balmoral Road') 
    get <- GET(url = 'https://platform.realestate.co.nz/search/v1/suggest/property', query = params) 
    json <- fromJSON(paste(get, collapse="")) 
    base <- 'https://www.realestate.co.nz/profile/' 
    print(paste0(base, json$data[[1]]$slug))
    

    派:

    import requests
    
    params = (('q', '4/271 Balmoral Road'),)
    r = requests.get('https://platform.realestate.co.nz/search/v1/suggest/property' , params=params).json()
    links = [f"https://www.realestate.co.nz/profile/{i['slug']}" for i in r['data']]
    print(links[0])
    

    【讨论】:

    • 非常感谢 QHarr。我试过你的 R 脚本,但没有用。但是,它就像这样library(httr) library(jsonlite) params = list('q' = '4/271 Balmoral Road') get &lt;- GET(url = 'https://platform.realestate.co.nz/search/v1/suggest/property', query = params) json &lt;- fromJSON(paste(get, collapse="")) base &lt;- 'https://www.realestate.co.nz/profile/' print(paste0(base, json$data[[1]]$slug)) 无论如何谢谢:)
    • 不知道为什么不适合你,因为对我来说很好,但很高兴知道还有另一种方法:-)
    • 可能版本不同?我上传了其他问题,如果您能再次帮助我,那就太好了。 stackoverflow.com/questions/58655930/…
    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 2016-04-25
    • 2018-05-09
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多