Scrapy + Splash:在内部 html 内抓取元素
Scrapy + Splash: scraping element inside inner html
我正在使用 Scrapy + Splash 抓取网页并尝试从 google 广告横幅和其他广告中提取数据,但我很难按照 xpath 进入它们。
我正在使用 Scrpay-Splash API to render the pages so their scripts and images load and to take screenshots but it seems google ad banners are created by JS scripts that then insert their contents into a new html document within an iframe in the webpage, as so:
Splash 确保代码已呈现,因此我不会 运行 遇到 scrapy 与脚本有关的常见问题,它读取脚本的内容而不是结果 html -- 但我可以似乎找不到一种方法来指示到达我需要的元素节点所需的 XPath(广告的 href link)。
如果我检查 google 中的元素并复制它的 xpath,它只会给我 //*[@id="aw0"]
,如果这里只有 iframe 的 html,我觉得这会起作用,但是无论我怎么写,它 returns 都是空的,我觉得这可能是因为 XPath 不能优雅地处理堆叠在 html 文档中的 html 文档。
包含 google 广告代码的 iframe 的 XPath 是
//*[@id="google_ads_iframe_/87824813/hola/blogs/home_0"]
{数字不变}。
有没有办法将这些 XPath 堆叠在一起,以便快速跟踪进入我需要的容器?或者我应该以其他方式直接解析 Splash 响应对象而我不能依赖 Response.Xpath/Response.CSS 吗?
问题是 iframe 内容没有作为 html 的一部分返回。您可以尝试直接获取 iframe 内容(通过其 src),或使用带有 iframes=1 选项的 render.json 端点:
# ...
yield SplashRequest(url, self.parse_result, endpoint='render.json',
args={'html': 1, 'iframes': 1})
def parse_result(self, response):
iframe_html = response.data['childFrames'][0]['html']
sel = parsel.Selector(iframe_html)
item = {
'my_field': sel.xpath(...),
# ...
}
/execute
从 Splash 2.3.3 开始端点不支持获取 iframe 内容。
另一种处理 iframe 的方法可以是(响应主页):
urls = response.css('iframe::attr(src)').extract()
for url in urls :
parse the url
通过这种方式,iframe 就像普通页面一样被解析,
但目前我无法将主页中的 cookie 发送到 iframe 中的 html,这是个问题
我正在使用 Scrapy + Splash 抓取网页并尝试从 google 广告横幅和其他广告中提取数据,但我很难按照 xpath 进入它们。
我正在使用 Scrpay-Splash API to render the pages so their scripts and images load and to take screenshots but it seems google ad banners are created by JS scripts that then insert their contents into a new html document within an iframe in the webpage, as so:
Splash 确保代码已呈现,因此我不会 运行 遇到 scrapy 与脚本有关的常见问题,它读取脚本的内容而不是结果 html -- 但我可以似乎找不到一种方法来指示到达我需要的元素节点所需的 XPath(广告的 href link)。
如果我检查 google 中的元素并复制它的 xpath,它只会给我 //*[@id="aw0"]
,如果这里只有 iframe 的 html,我觉得这会起作用,但是无论我怎么写,它 returns 都是空的,我觉得这可能是因为 XPath 不能优雅地处理堆叠在 html 文档中的 html 文档。
包含 google 广告代码的 iframe 的 XPath 是
//*[@id="google_ads_iframe_/87824813/hola/blogs/home_0"]
{数字不变}。
有没有办法将这些 XPath 堆叠在一起,以便快速跟踪进入我需要的容器?或者我应该以其他方式直接解析 Splash 响应对象而我不能依赖 Response.Xpath/Response.CSS 吗?
问题是 iframe 内容没有作为 html 的一部分返回。您可以尝试直接获取 iframe 内容(通过其 src),或使用带有 iframes=1 选项的 render.json 端点:
# ...
yield SplashRequest(url, self.parse_result, endpoint='render.json',
args={'html': 1, 'iframes': 1})
def parse_result(self, response):
iframe_html = response.data['childFrames'][0]['html']
sel = parsel.Selector(iframe_html)
item = {
'my_field': sel.xpath(...),
# ...
}
/execute
从 Splash 2.3.3 开始端点不支持获取 iframe 内容。
另一种处理 iframe 的方法可以是(响应主页):
urls = response.css('iframe::attr(src)').extract()
for url in urls :
parse the url
通过这种方式,iframe 就像普通页面一样被解析, 但目前我无法将主页中的 cookie 发送到 iframe 中的 html,这是个问题