基础篇(6) splash应用

2024-08-28 18:58
文章标签 基础 应用 splash

本文主要是介绍基础篇(6) splash应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

     selenium是浏览器测试自动化工具,很容易完成鼠标点击,翻页等动作,确定是一次只能加载一个页面,无法异步渲染页面,也就限制了selenium爬虫的抓取效率。

    splash可以实现异步渲染页面,可以同时渲染几个页面。缺点是在页面点击,,模拟登陆方面没有selenium灵活。

1、docker安装splash

docker安装splash镜像
[ywadmin@wzy_woyun ~]$docker pull scrapinghub/splash
#后台运行
[ywadmin@wzy_woyun ~]$ docker run -d -p 8050:8050 --name=splash scrapinghub/splash
#root用户开放8050端口
[root@wzy_woyun ~]# firewall-cmd --permanent --add-port=8050/tcp
success
[root@wzy_woyun ~]# firewall-cmd --reload
Success

2、splash中的对象

2.1、args属性

该属性可以获取加载时配置的参数,比如url。

function main(splash, args)

      local url = args.url

end

上面的代码等同于下面

function main(splash, args)

      local url = splash.args.url

end

3.2、js_enabled属性

接着我们重新代用eval()方法执行JavaScript代码,运行时发现报错。这个属性是splash的JavaScript执行开关,可以将其配置为true或者false来控制是否执行JavaScript代码,默认为true

function main(splash, args)splash:go("https://www.baidu.com")splash:js_enabled = false -- 禁止加载JavaScript代码splash:wait(0.5)local title = splash:evaljs("document.title") --获取网页标题return {html = splash:html(),title = title,   }
end

接着我们重新代用eval()方法执行JavaScript代码,运行时发现报错。

一般不用设置次属性,默认是开启的。

2.3、resource_timeout属性

属性可以设置加载的超时时间,单位是秒。如果设置为0或者nil(类似py中的None),表示不进行超时检测。

function main(splash, args)splash.resource_timeout = 5splash:go("https://www.taobao.com")return splash:html()
end

2.4、images_enabled属性

    images_enabled属性表示可以设置图片是否加载,默认情况下是加载的,默认为true。如果设置图片不加载,那么加载网页速度会快。

function main(splash, args)splash.images_enabled = falsesplash:go("https://www.taobao.com")return {splash:html(),splash.png}
end

2.5、plugins_enabled属性

该属性表示是否开启浏览器插件。默认情况是开启,默认值为true。

function main(splash, args)splash.plugins_enabled = falsesplash:go("https://www.taobao.com")return {splash:html(),splash.png(),}
end

2.6、scroll_position属性

控制浏览页面上下或者左右滚动,这个属性是比较常用的属性。

function main(splash, args) splash:go("https://www.taobao.com")splash.scroll_postion={x=300,y=500}return {splash:html(),splash.png()}
end

其中x=300表示向右移动300像素,y=500表示向下移动500像素。

3、splash中的方法

3.1、go()方法

go方法用来请求某个链接,而且它可以模拟get和post请求,同时支持传入请求头、表单等数据。

function main(splash)splash:go{"http://www.sxt.cn", http_method="POST", body="name=17703181473"}splash:wait(2)return {html=splash:html()}
end

3.2、wait()方法

wait()方法控制页面的等待时间:

splash:wait{time, cancel_on_redirect=false, cancel_on_error=true}

function main(splash)splash:go("https://www.taobao.com")splash:wait(2)return {html=splash:html()}
end

3.3、jsfunc()方法

直接调用JavaScript定义的方法,但是所调用的方法需要用双中括号包围,这相当于实现了JavaScript方法到Lua脚本的转换。

function main(splash, args)splash:go("http://www.baidu.cn")local scroll_to = splash:jsfunc("window.scrollTo")scroll_to(0, 300)return {png = splash:png(),html = splash:html()}
end

3.4、evaljs()方法和runjs()方法

function main(splash, args)splash:go("https://www.baidu.com")splash:runjs("foo = function() { return 'sxt' }")local result = splash:evaljs("foo()")return result
end

3.5、send_text()

send_text()方法是填写文本的功能

function main(splash)splash:go("https://www.baidu.com/")input = splash:select("#kw")input:send_text('Splash')splash:wait(3)return splash:png()
end

3.6、url()方法

获取当前在访问的URL

function main(splash, args)splash:go("https://www.baidu.com")return splash:url()
end

3.7、get_cookies()方法

function main(splash, args)splash:go("http://www.baidu.com")splash:wait(2)local cookies = splash:get_cookies()return {cookies = cookies,html = splash:html(),png = splash:png(),har = splash:har(),}
end

 

3.7、  add_cookie()方法

添加cookies

【语法】

cookies = splash:add_cookie{name, value, path=nil, domain=nil, expires=nil, httpOnly=nil, secure=nil}

function main(splash)splash:add_cookie{"sessionid", "123456abcdef", "/", domain="http://bjsxt.com"}splash:go("http://bjsxt.com/")return splash:html()
end

3.8、clear_cookies()方法

function main(splash)splash:go("https://www.bjsxt.com/")splash:clear_cookies()return splash:get_cookies()
end

3.9、set_user_agent()方法

 

function main(splash, args)splash:set_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36")splash:go("http://httpbin.org/get")splash:wait(5)return {html = splash:html(),png = splash:png(),   }
end

注意set_user_agent()方法后面直接跟具体的值。

3.10、set_custom_headers()方法

set_custom_headers()方法是用来设置请求头信息。

function main(splash, args)splash:set_custom_headers({["User-Agent"]="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",["Host"]="www.httpbin.org"})splash:go("http://httpbin.org/get")splash:wait(5)return {html = splash:html(),png = splash:png(),   }
end

4、splash与python整合

Splash与Python结合其实就python调用splash的api。

4.1、render.html应用

import requests
from urllib.parse import quote
# 1、render.html
# 次接口用于获取JavaScript渲染的页面的HTML代码,接口地址就是Splash的运行地址加次接口名称,如http://192.168.2.10:8050/render.html
url = "http://192.168.2.10:8050/render.html?url=http://www.hnwznz.com&wait=2"
response = requests.get(url)
print(response.text)# 2、render.png 此接口可以获取网页截图
url_2= "http://192.168.2.10:8050/render.png?url=https://www.jd.com&wait=3&width=1000&height=700"
response_2 = requests.get(url_2)
with open("jd.png","wb") as f:f.write(response.content)

4.2、execute的调用

#3、execute 作为最强大的接口,用次接口便可实现与Lua脚本的对接。lua = """
function main(splash, args)return "hello"
end
"""
url_3 = "http://192.168.2.10:8050/execute?lua_source="+quote(lua)
response_3 = requests.get(url_3)
print(response_3.text)

【例子】

import requests
from fake_useragent import UserAgent
from urllib.parse import quote
url = "https://www.guazi.com/bj/buy/"
lua_script = '''
function main(splash, args)splash:go('{}')splash:wait(1)return splash:html()
end
'''.format(url)
splash_url = "http://192.168.2.10:8050/execute?lua_source={}".format(quote(lua_script))
response = requests.get(splash_url, headers={"User-Agent": UserAgent().random})
response.encoding = 'utf-8'
print(response.text)

5、应用例子

5.1、爬取京东商品

import json
import requests
from lxml import etree
from urllib.parse import quote
lua = '''
function main(splash, args)local treat = require("treat")local response = splash:http_get("https://search.jd.com/Search?keyword=相机&enc=utf-8")return {html = treat.as_string(response.body),url = response.url,status = response.status}    
end
'''
# 线上部署的服务,需要将localhost换成服务器的公网地址(不是内网地址)
url = 'http://192.168.2.10:8050/execute?lua_source=' + quote(lua)
response = requests.get(url)
# 由于使用splash,response.text返回结果为{"status":200,"html":"xxxxxxxxx","url":"yyyyyy"}
html = json.loads(response.text)['html']
# print(html)
tree = etree.HTML(html)# 单品
products_1 = tree.xpath('//div[@class="gl-i-wrap"]')
for item in products_1:try:name_1 = item.xpath('./div[@class="p-name p-name-type-2"]/a/em/text()')[0]price_1 = item.xpath('./div[@class="p-price"]/strong/@data-price | ./div[@class="p-price"]/strong/i/text()')[0]print(name_1)print(price_1)except:pass
print("="*90)

 

 

这篇关于基础篇(6) splash应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1115606

相关文章

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

从基础到进阶详解Pandas时间数据处理指南

《从基础到进阶详解Pandas时间数据处理指南》Pandas构建了完整的时间数据处理生态,核心由四个基础类构成,Timestamp,DatetimeIndex,Period和Timedelta,下面我... 目录1. 时间数据类型与基础操作1.1 核心时间对象体系1.2 时间数据生成技巧2. 时间索引与数据

安装centos8设置基础软件仓库时出错的解决方案

《安装centos8设置基础软件仓库时出错的解决方案》:本文主要介绍安装centos8设置基础软件仓库时出错的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录安装Centos8设置基础软件仓库时出错版本 8版本 8.2.200android4版本 javas

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”

Linux基础命令@grep、wc、管道符的使用详解

《Linux基础命令@grep、wc、管道符的使用详解》:本文主要介绍Linux基础命令@grep、wc、管道符的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录grep概念语法作用演示一演示二演示三,带选项 -nwc概念语法作用wc,不带选项-c,统计字节数-

如何确定哪些软件是Mac系统自带的? Mac系统内置应用查看技巧

《如何确定哪些软件是Mac系统自带的?Mac系统内置应用查看技巧》如何确定哪些软件是Mac系统自带的?mac系统中有很多自带的应用,想要看看哪些是系统自带,该怎么查看呢?下面我们就来看看Mac系统内... 在MAC电脑上,可以使用以下方法来确定哪些软件是系统自带的:1.应用程序文件夹打开应用程序文件夹

python操作redis基础

《python操作redis基础》Redis(RemoteDictionaryServer)是一个开源的、基于内存的键值对(Key-Value)存储系统,它通常用作数据库、缓存和消息代理,这篇文章... 目录1. Redis 简介2. 前提条件3. 安装 python Redis 客户端库4. 连接到 Re

Python Flask 库及应用场景

《PythonFlask库及应用场景》Flask是Python生态中​轻量级且高度灵活的Web开发框架,基于WerkzeugWSGI工具库和Jinja2模板引擎构建,下面给大家介绍PythonFl... 目录一、Flask 库简介二、核心组件与架构三、常用函数与核心操作 ​1. 基础应用搭建​2. 路由与参

Spring Boot中的YML配置列表及应用小结

《SpringBoot中的YML配置列表及应用小结》在SpringBoot中使用YAML进行列表的配置不仅简洁明了,还能提高代码的可读性和可维护性,:本文主要介绍SpringBoot中的YML配... 目录YAML列表的基础语法在Spring Boot中的应用从YAML读取列表列表中的复杂对象其他注意事项总

电脑系统Hosts文件原理和应用分享

《电脑系统Hosts文件原理和应用分享》Hosts是一个没有扩展名的系统文件,当用户在浏览器中输入一个需要登录的网址时,系统会首先自动从Hosts文件中寻找对应的IP地址,一旦找到,系统会立即打开对应... Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址域名与其对应