Scrapy + splash: can't select 元素
Scrapy + splash: can't select element
我正在学习将 scrapy 与 splash 一起使用。作为练习,我尝试访问 https://www.ubereats.com/stores/,单击地址文本框,输入位置,然后按 Enter 按钮移至下一页,其中包含该位置可用的餐厅。我有以下 lua 代码:
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(5))
local element = splash:select('.base_29SQWm')
local bounds = element:bounds()
assert(element:mouseclick{x = bounds.width/2, y = bounds.height/2})
assert(element:send_text("Wall Street"))
assert(splash:send_keys("<Return>"))
assert(splash:wait(5))
return {
html = splash:html(),
}
end
当我在初始 API 中单击 "Render!" 时,我收到以下错误消息:
{
"info": {
"message": "Lua error: [string \"function main(splash)\r...\"]:7: attempt to index local 'element' (a nil value)",
"type": "LUA_ERROR",
"error": "attempt to index local 'element' (a nil value)",
"source": "[string \"function main(splash)\r...\"]",
"line_number": 7
},
"error": 400,
"type": "ScriptError",
"description": "Error happened while executing Lua script"
}
不知何故,我的 css 表达式是错误的,导致试图访问 undefined/nil 元素时出现飞溅!我试过其他表达方式,但我似乎无法理解!
问:有谁知道如何解决这个问题?
编辑:尽管我仍然想知道如何实际点击该元素,但我想出了如何通过使用键来获得相同的结果:
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(5))
splash:send_keys("<Tab>")
splash:send_keys("<Tab>")
splash:send_text("Wall Street, New York")
splash:send_keys("<Return>")
assert(splash:wait(10))
return {
html = splash:html(),
png = splash:png(),
}
end
但是,启动画面 API 中返回的 html/images 来自您输入地址的页面,而不是您输入地址并单击回车后看到的页面。
Q2:如何成功加载第二页?
不是一个完整的解决方案,但这是我目前所拥有的:
import json
import re
import scrapy
from scrapy_splash import SplashRequest
class UberEatsSpider(scrapy.Spider):
name = "ubereatspider"
allowed_domains = ["ubereats.com"]
def start_requests(self):
script = """
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(10))
splash:set_viewport_full()
local search_input = splash:select('#address-selection-input')
search_input:send_text("Wall Street, New York")
assert(splash:wait(5))
local submit_button = splash:select('button[class^=submitButton_]')
submit_button:click()
assert(splash:wait(10))
return {
html = splash:html(),
png = splash:png(),
}
end
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36'
}
yield SplashRequest('https://www.ubereats.com/new_york/', self.parse, endpoint='execute', args={
'lua_source': script,
'wait': 5
}, splash_headers=headers, headers=headers)
def parse(self, response):
script = response.xpath("//script[contains(., 'cityName')]/text()").extract_first()
pattern = re.compile(r"window.INITIAL_STATE = (\{.*?\});", re.MULTILINE | re.DOTALL)
match = pattern.search(script)
if match:
data = match.group(1)
data = json.loads(data)
for place in data["marketplace"]["marketplaceStores"]["data"]["entity"]:
print(place["title"])
注意 Lua 脚本中的变化:我找到了搜索输入,将搜索文本发送给它,然后找到 "Find" 按钮并单击它。在屏幕截图上,无论我设置的时间延迟如何,我都没有看到加载的搜索结果,但我已经设法从 script
内容中获取了餐厅名称。 place
对象包含过滤所需餐厅的所有必要信息。
另请注意,我导航到的 URL 是
"New York"一个(不是一般的"stores")。
虽然我不完全确定为什么没有加载搜索结果页面,但希望这对您来说是一个好的开始,您可以进一步改进此解决方案。
我正在学习将 scrapy 与 splash 一起使用。作为练习,我尝试访问 https://www.ubereats.com/stores/,单击地址文本框,输入位置,然后按 Enter 按钮移至下一页,其中包含该位置可用的餐厅。我有以下 lua 代码:
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(5))
local element = splash:select('.base_29SQWm')
local bounds = element:bounds()
assert(element:mouseclick{x = bounds.width/2, y = bounds.height/2})
assert(element:send_text("Wall Street"))
assert(splash:send_keys("<Return>"))
assert(splash:wait(5))
return {
html = splash:html(),
}
end
当我在初始 API 中单击 "Render!" 时,我收到以下错误消息:
{
"info": {
"message": "Lua error: [string \"function main(splash)\r...\"]:7: attempt to index local 'element' (a nil value)",
"type": "LUA_ERROR",
"error": "attempt to index local 'element' (a nil value)",
"source": "[string \"function main(splash)\r...\"]",
"line_number": 7
},
"error": 400,
"type": "ScriptError",
"description": "Error happened while executing Lua script"
}
不知何故,我的 css 表达式是错误的,导致试图访问 undefined/nil 元素时出现飞溅!我试过其他表达方式,但我似乎无法理解!
问:有谁知道如何解决这个问题?
编辑:尽管我仍然想知道如何实际点击该元素,但我想出了如何通过使用键来获得相同的结果:
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(5))
splash:send_keys("<Tab>")
splash:send_keys("<Tab>")
splash:send_text("Wall Street, New York")
splash:send_keys("<Return>")
assert(splash:wait(10))
return {
html = splash:html(),
png = splash:png(),
}
end
但是,启动画面 API 中返回的 html/images 来自您输入地址的页面,而不是您输入地址并单击回车后看到的页面。
Q2:如何成功加载第二页?
不是一个完整的解决方案,但这是我目前所拥有的:
import json
import re
import scrapy
from scrapy_splash import SplashRequest
class UberEatsSpider(scrapy.Spider):
name = "ubereatspider"
allowed_domains = ["ubereats.com"]
def start_requests(self):
script = """
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(10))
splash:set_viewport_full()
local search_input = splash:select('#address-selection-input')
search_input:send_text("Wall Street, New York")
assert(splash:wait(5))
local submit_button = splash:select('button[class^=submitButton_]')
submit_button:click()
assert(splash:wait(10))
return {
html = splash:html(),
png = splash:png(),
}
end
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36'
}
yield SplashRequest('https://www.ubereats.com/new_york/', self.parse, endpoint='execute', args={
'lua_source': script,
'wait': 5
}, splash_headers=headers, headers=headers)
def parse(self, response):
script = response.xpath("//script[contains(., 'cityName')]/text()").extract_first()
pattern = re.compile(r"window.INITIAL_STATE = (\{.*?\});", re.MULTILINE | re.DOTALL)
match = pattern.search(script)
if match:
data = match.group(1)
data = json.loads(data)
for place in data["marketplace"]["marketplaceStores"]["data"]["entity"]:
print(place["title"])
注意 Lua 脚本中的变化:我找到了搜索输入,将搜索文本发送给它,然后找到 "Find" 按钮并单击它。在屏幕截图上,无论我设置的时间延迟如何,我都没有看到加载的搜索结果,但我已经设法从 script
内容中获取了餐厅名称。 place
对象包含过滤所需餐厅的所有必要信息。
另请注意,我导航到的 URL 是 "New York"一个(不是一般的"stores")。
虽然我不完全确定为什么没有加载搜索结果页面,但希望这对您来说是一个好的开始,您可以进一步改进此解决方案。