问题出在网站上
您的 xpath 看起来不错,但网站 HTML 却不行!
如果您在此网站上使用 HTML 验证器:
https://validator.w3.org/nu/?doc=https%3A%2F%2Fwww.jelliscraig.com.au%2Fproperty-details-228A-Victoria-Street-Ballarat-East%2F1042039 https://validator.w3.org/nu/?doc=https%3A%2F%2Fwww.jelliscraig.com.au%2Fproperty-details-228A-Victoria-Street-Ballarat-East%2F1042039
您将看到它有很多错误,对于 XML 来说最严重的是,它有杂散标签。因此,在大多数情况下,XML 解析器要么会感到困惑,要么将其视为无效而拒绝。
我尝试了一堆不同的 xpath 但找不到任何img
标记任何地方,即使为所有内容创建 x 路径/
or /*
- 这告诉我这个 HTML 可能格式不正确,XML 解析器无法读取它。
解决方法
=REGEXEXTRACT(
IMPORTXML(
"https://www.jelliscraig.com.au/property-details-228A-Victoria-Street-Ballarat-East/1042039",
"/"
),
"https:\/\/images\.listonce.+\.jpg"
)
通过查看结果我发现了什么/
x-path 的问题是该链接似乎在其他几个地方被引用。也许这对于大多数网站来说都是一致的,并且最有可能的是,所有图像都由相同的 URL 格式提供:
https://images.listonce.com.au ... jpg
因此,使用此信息您可以包装IMPORTXML
in a REGEXEXTRACT https://support.google.com/docs/answer/3098244并使用松散的正则表达式,例如:
https:\/\/images\.listonce.+\.jpg
对于您提供的示例 URL,将返回:
https://images.listonce.com.au/custom/m/listings/228a-victoria-street-ballarat-east-vic-3350/039/01042039_img_01.jpg https://images.listonce.com.au/custom/m/listings/228a-victoria-street-ballarat-east-vic-3350/039/01042039_img_01.jpg
这似乎就是您正在寻找的图像。
应用程序脚本
也许调查一下应用程序脚本 https://developers.google.com/apps-script/overview特别是网址获取应用程序 https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app。使用这些工具,您将可以更好地控制所获取的 HTML,并为您提供更多的数据抓取选项。
这是相同流程但使用 Apps 脚本的示例
function getImageUrl() {
// Fetch the website
let response = UrlFetchApp.fetch("https://www.jelliscraig.com.au/property-details-228A-Victoria-Street-Ballarat-East/1042039")
// Get the text from the response
let html = response.getContentText()
// Use Regex to Match the Tag
let result = html.match(/(?<=img src=.+)https:\/\/images.listonce.com.au\/.+\.jpg/)
// Log the first result
Logger.log(result[0])
}
哪个会记录https://images.listonce.com.au/custom/l/listings/228a-victoria-street-ballarat-east-vic-3350/039/01042039_img_01.jpg
参考
- REGEXEXTRACT https://support.google.com/docs/answer/3098244
- Apps 脚本概述 https://developers.google.com/apps-script/overview
- 网址获取应用程序 https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app