Python爬虫:splash+requests简单示例
2023-09-14 09:07:14 时间
说明:
render是get方式
execute是post方式
render
import requests
def splash_render(url):
splash_url = "http://localhost:8050/render.html"
args = {
"url": url,
"timeout": 5,
"image": 0,
"proxy": "http://222.95.21.28:8888"
}
response = requests.get(splash_url, params=args)
return response.text
if __name__ == '__main__':
url = "http://quotes.toscrape.com/js/"
html = splash_render(url)
args参数说明:
url: 需要渲染的页面地址
timeout: 超时时间
proxy:代理
wait:等待渲染时间
images: 是否下载,默认1(下载)
js_source: 渲染页面前执行的js代码
execute
import json
import requests
def splash_execute(url):
splash_url = "http://localhost:8050/execute"
script = """
function main(splash)
local url="{url}"
splash:set_user_agent("Mozilla/5.0 Chrome/69.0.3497.100 Safari/537.36")
splash:go(url)
splash:wait(2)
splash:go(url)
return {
html = splash:html()
}
end
"""
script = script.replace("{url}", url)
data = {
"timeout": 5,
"lua_source": script
}
response = requests.post(splash_url, json=data)
return response.json().get("html")
if __name__ == '__main__':
url = "http://quotes.toscrape.com/js/"
html = splash_execute(url)
参数说明:
timeout 超时
lua_source lua脚本
proxy 代理
模拟登录
以下是lua脚本
splash提供的select选择器,使用方法和jQuery类似
function main(splash, args)
-- jquery加载比较慢
splash:autoload("https://code.jquery.com/jquery-3.3.1.min.js")
splash:set_viewport_size(1366, 768)
splash:set_user_agent("Mozilla/5.0 Chrome/69.0.3497.100 Safari/537.36")
-- 从首页点击登录按钮
splash:go(splash.args.url)
splash:wait(3)
splash:runjs("$('#login').click()")
splash:wait(2)
-- 登录页输入账号密码,并提交
splash:select("#username"):send_text("username")
splash:select("#password"):send_text("password")
splash:wait(5)
-- 可以使用splash自带的鼠标点击,并指定点击位置
local button = splash:select("#button")
local bounds = button:bounds()
button:mouse_click{x=bounds.width/3, y=bounds.height/3}
splash:wait(2)
-- 返回
return {
html=splash:html(),
png = splash:png(),
cookie=splash:get_cookies()
}
end
参考:
splash文档:https://splash.readthedocs.io/en/stable/scripting-ref.html
相关文章
- python和pythoncharm有什么区别_python为什么叫爬虫
- python win32api messagebox_如何在Python中使用Win32 API?
- Python爬虫常用:谷歌浏览器驱动——Chromedriver 插件安装教程
- python中bool函数_bool()函数以及Python中的示例
- 这是我见过最牛逼的接口自动化测试框架没有之一:基于python+requests+pytest+allure实现
- Python(一)对 meta class 的理解
- {Python}关于类属性、类方法和静态方法的综合案例
- python输出unicode编码_Python以utf8编码读取文件
- python语言关键字是_Python 关键字
- python程序化交易实例-用 Python 实现你的量化交易策略「建议收藏」
- 下列python语句的输出结果是print_下列 Python语句的输出结果是「建议收藏」
- python使用opencv如何保存图片_OpenCV Python 保存图片
- Python爬虫,最新的B站弹幕和评论爬虫,你们要的冰冰来啦!
- Python爬虫-爬取彼岸图库图片案例
- “可在浏览器端运行的Python”,再发力!!!
- Python多线程爬虫编程中queue.Queue和queue.SimpleQueue的区别和应用
- Python 自动化指南(繁琐工作自动化)第二版:八、输入验证
- Python IDE有哪些,哪款适合初学者?
- python字符串加密解密的三种方法分享(base64win32com)