gpt4 book ai didi

xpath - Scrapy + Splash:在内部html内抓取元素

转载 作者:行者123 更新时间:2023-12-03 17:10:15 27 4
gpt4 key购买 nike

我正在使用Scrapy + Splash来爬网网页,并尝试从google广告横幅和其他广告中提取数据,但是我很难弄清楚要遵循xpath的方式。

我正在使用Scrpay-Splash API渲染页面,以便加载其脚本和图像并获取屏幕截图,但是看来Google广告横幅是由JS脚本创建的,然后将其内容插入网页中iframe中的新html文档中,这样:The red area is the iframe container, the blue shows the link I want to extract

Splash可以确保代码已呈现,因此我不会遇到脚本读取其内容而不是生成的html的脚本经常遇到的问题-但我似乎无法找到一种方法来指示必要的XPath到达我需要的元素节点(广告的href链接)。

如果我检查google中的元素并复制它的xpath,它只会给我//*[@id="aw0"],如果iframe的html在那里,我觉得这可以工作,但是无论我怎么写它都会返回空,我觉得这可能是因为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),也可以将render.json端点与iframes = 1选项一起使用:

# ...
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(...),
# ...
}


从Splash 2.3.3开始, /execute端点不支持获取iframe内容。

关于xpath - Scrapy + Splash:在内部html内抓取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44657613/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com