如何通过Swift从谷歌搜索结果页面URL中提取搜索关键词?

时间:2022-08-22 11:24:38

How do you extract search keywords from Google search result page URL by Swift?

如何通过Swift从谷歌搜索结果页面URL中提取搜索关键词?

I was simply trying to get stings after "&q=" but I found out I needed to consider more complicated cases such as "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"

我只是想在“&q=”之后得到一些刺痛感,但我发现我需要考虑更复杂的情况,比如“https://www.google.co.jp/search?”

I would appreciate your advice.

谢谢你的建议。

Update: As per advised by LEO, I put this way.

更新:根据LEO的建议,我是这么说的。

if let url = NSURL(string: urlStr){

        var extractedQuery = ""
        if let fragment = url.fragment {
            extractedQuery = fragment
        } else if let query = url.query{
            extractedQuery = query
        }


        if let queryRange = extractedQuery.rangeOfString("&q="){
            let queryStartIndex = queryRange.endIndex
            let queryKeyword = extractedQuery.substringFromIndex(queryStartIndex)
            print(queryKeyword)
        }
    }

1 个解决方案

#1


1  

You can convert your string to NSURL and access its query and fragment properties:

您可以将您的字符串转换为NSURL并访问其查询和片段属性:

if let url = NSURL(string: "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"), query = url.query, fragment = url.fragment {
    print(query)    // "hl=ja&q=test\n"
    print(fragment) // "q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d\n"
}

#1


1  

You can convert your string to NSURL and access its query and fragment properties:

您可以将您的字符串转换为NSURL并访问其查询和片段属性:

if let url = NSURL(string: "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"), query = url.query, fragment = url.fragment {
    print(query)    // "hl=ja&q=test\n"
    print(fragment) // "q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d\n"
}