scrapy-splash模拟鼠标点击
跟网上其他教程一样,配置好scrapy
和splash
,
网上的教程大多都没提及这一点,都是用的render.html
,但是这个没法执行lua_source
的脚本
重写 start_requests
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import scrapy
from scrapy_splash import SplashRequest
from scrapy_splash import SplashMiddleware
# 模拟点击采用js的方式
script = """
function main(splash, args)
splash.images_enabled = false
assert(splash:go(args.url))
assert(splash:wait(1))
js = string.format("document.querySelector('#sxxz > li:nth-child(3) > a').click();", args.page)
splash:runjs(js)
assert(splash:wait(1))
return splash:html()
end
"""
class TestSpider(scrapy.Spider):
name = 'sspider'
start_urls = ['http://www.gdzwfw.gov.cn/portal/branch-hall?orgCode=006940060#']
def start_requests(self):
for url in self.start_urls:
# endpoint其他教程都是写的render.html,但是模拟点击需要修改为 '/execute'
yield SplashRequest(url=url, callback=self.parse_m, endpoint='execute', args={
'wait': 10, 'images': 0, 'lua_source': script
})
def parse_m(self, response):
# print(response.text)
# print(response.encoding)
print(response.xpath('//*[@id="branch-tab1"]').extract()[0])
重点就是 endpoint
这个参数
- render.html:是 Return the HTML of the javascript-rendered page. (返回javascript呈现页面的HTML。)
- render.png:是 Return an image (in PNG format) of the javascript-rendered page.(返回javascript呈现页面的图像(PNG格式)。)
- render.jpeg
- render.har
- render.json
- execute: Execute a custom rendering script and return a result.(执行自定义渲染脚本并返回结果。)
详细可参考 官方文档