我正在尝试使用 Google 图片抓取反向图片搜索的结果。
我的起始网址是 https://www.google.com/searchbyimage?image_url=DIRECT_IMAGE_URL ,在浏览器中按预期工作。
但是,当我尝试通过 Scrapy 抓取它时,请求被重定向了 3 次,如图所示;
生成的网页看起来像
而不是结果页面。这是我的 Scrapy settings.py
SPLASH_URL = 'http://splash:8050'
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
REDIRECT_MAX_TIMES = 2
HTTPCACHE_ENABLED = True
我考虑过;
- 缺少 Javascript - 所以我使用 Splash 来呈现页面
- Cookie - 我认为它有用?
- 设置最大重定向次数 - 没用
这是我对 SplashRequest 的调用;
yield SplashRequest(url, self.parse, meta={
'cookiejar': i,
'wait': 0.5,
'splash': {
'args': {
'html': 1,
'png': 1,
},
'splash_headers': {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'
} # optional; a dict with headers sent to Splash
}
知道是什么导致了 3 次重定向吗?第一个重定向对于结果是必需的,但第二个和第三个不是,并且给我错误的页面。
最佳答案
我想通了!我的错误在用户代理中。我以为我正在设置 User-Agent,但实际上我是在为发送到 Splash 的请求设置 header ,而不是为实际发送到我想抓取的页面的请求。
为了让它工作,我改变了
yield SplashRequest(url, self.parse, meta={
'cookiejar': i,
'wait': 0.5,
'splash': {
'args': {
'html': 1,
'png': 1,
},
'splash_headers': {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'
} # optional; a dict with headers sent to Splash
}
})
到
yield SplashRequest(url, self.parse, meta={
'cookiejar': i,
'wait': 0.5,
'splash': {
'args': {
'html': 1,
'png': 1,
}
},
}, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'})
关于python - 使用 Scrapy/Splash 抓取 Google 图像 - 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44021317/