【发布时间】:2018-01-12 18:06:57
【问题描述】:
Google 图片搜索返回如下结果链接:
<div class="rg_meta notranslate">{"cb":6,"cl":21,"cr":9,"ct":6,"id":"G9X757bOKIt_dM:","isu":"hitparade.ch","itg":0,"ity":"jpg","oh":300,"ou":"http://streamd.hitparade.ch/cdimages/jennifer_rush-i_come_undone_s.jpg","ow":296,"pt":"Jennifer Rush - I Come Undone - hitparade.ch","rid":"xArn9C5TiVuF9M","rmt":0,"rt":0,"ru":"http://hitparade.ch/song/Jennifer-Rush/I-Come-Undone-1581","s":"Jennifer Rush - I Come Undone","sc":1,"st":"Hitparade.ch","th":226,"tu":"https://encrypted-tbn0.gstatic.com/images?q\u003dtbn:ANd9GcRbLwVl711N3Q93C-SFdj1a1X6CLQIohPbb_8G9eBEJBX_bzQdC","tw":223}</div>
如何正确获取此 div 中的图像路径(在“ou”字段中)
rg_meta
与斯威夫特和卡纳? 我尝试了几种变体,例如
// Alamofire.request...
if let doc = Kanna.HTML(html: html, encoding: String.Encoding.utf8) {
for item in doc.xpath("//div[@class='rg_meta']") {
print(item.text)
print(item["ou"])
}
}
但该项目始终为空。这是 div 中的 Json 数据吗?有没有办法用 Kanna 获得“ou”字段? 谢谢。
编辑: 生成 html 以测试 xpath 表达式的示例如下:
https://www.google.com/search?q=jennifer+rush+i+come+undone&gbv=2&tbm=isch
编辑2:
好的,虽然 Adrians 的回答似乎正确捕获了“ou”字段中的 json 数据,但我的代码仍然无法按预期工作,我进行了更多调试:
正如我现在所看到的,我的主要问题似乎是我打算捕获的 div 类没有被 Alamofire 下载。似乎这是因为这不在 google 返回的 html 正文中,而是在我不理解的结构中。可以在搜索结果的源代码中看到。
到目前为止我的测试代码:
let requestUrl = "https://www.google.com/search?q=jennifer+rush+i+come+undone&gbv=2&tbm=isch"
Alamofire.request(requestUrl).responseString { response in
print("Request success/charcount: \(response.result.isSuccess) \(response.result.value?.characters.count ?? 0)")
if let responseHtml = response.result.value {
if let doc = Kanna.HTML(html: responseHtml, encoding: String.Encoding.utf8) {
for item in doc.xpath("//div[@class='rg_meta']") {
print(item.text ?? "---")
}
}
}
}
输出:
Request success/charcount: true 40830
下载了40k html,但在浏览器中查看的整个源代码约为600k。有什么方法可以下载所有内容,以便我可以搜索特殊的 div 类? 我试过了
Alamofire.request(requestUrl).responseData
和
Alamofire.download(requestUrl, to: destination)
同样,但都返回 40k html。
谢谢,
【问题讨论】:
-
您是否不需要在您的 xpath 表达式中包含“notranslate”(即
for item in doc.xpath("//div[@class='rg_meta notranslate']")?只需通过在线 xpath 测试器运行您的表达式并没有得到任何结果 -
不幸的是,添加 'notranslate' 并没有什么不同。