首页 > 编程问答 >我试图单击网站上的 java 脚本按钮,但它不起作用

我试图单击网站上的 java 脚本按钮,但它不起作用

时间:2024-07-30 15:46:20浏览次数:8  
标签:python web-scraping scrapy scrapy-splash

我通过lua中的这个脚本点击了按钮:

function main(splash)
            splash:init_cookies(splash.args.cookies)
            splash.private_mode_enabled = false
            splash.images_enabled = true  -- Ensure images are loaded
            assert(splash:go{
                splash.args.url,
                headers=splash.args.headers,
            })
            assert(splash:wait(5))  -- Increase wait time to ensure all resources are loaded

            splash:set_viewport_full()  -- Set viewport to full to capture the entire page
            local button = splash:select('.styles_desktop_button__container__BMM1C > button:nth-child(1)')
            
            if button then
                button:mouse_click()
                splash:wait(5)  -- Wait for images to load after clicking the button
            else
                return {
                    error = "Button not found",
                    url = splash:url(),
                    cookies = splash:get_cookies(),
                    html = splash:html(),
                    png = splash:png(),  -- Return the screenshot even if the button is not found
                }
            end

            local screenshot = splash:png()  -- Take a screenshot
            return {
                url = splash:url(),
                cookies = splash:get_cookies(),
                html = splash:html(),
                png = screenshot,  -- Return the screenshot
            }
        end

这是我用scrapy提取图像的代码

# the code for call parse_images

yield SplashRequest(response.url, self.parse_images, endpoint='execute',
                            args={"lua_source": script}, meta={"items": items}, headers=headers)





def parse_images(self, response):
        items = response.meta['items']

        screenshot_data = response.data['png']
        screenshot_bytes = base64.b64decode(screenshot_data)
        with open('screenshot.png', 'wb') as f:
            f.write(screenshot_bytes)

        if 'error' in response.data:
            self.logger.error(f"Error in Lua script: {response.data['error']}")
        else:
            html = response.data['html']
            soup = BeautifulSoup(html, 'html.parser')

            images = soup.find_all('img')
            lst2 = []
            jpg_pattern = re.compile(r'https:\/\/www\.propertyfinder\.ae\/property\/[a-zA-Z0-9\/\-\.\?\=]+')
            for img in images:
                src = img.get('src')
                if src and jpg_pattern.match(src):
                    lst2.append(src)

            items['image_urls'] = lst2

        yield items

我得到了屏幕截图,它显示点击没有发生。

在此处输入图像描述

这是我从代码中获得的屏幕截图。

如果您可以请调试我的代码,我在最后一天一直在研究它,但它仍然是这样。

感谢您的帮助。


代码似乎运作良好,问题可能出在你要点击的按钮的性质上,或者页面加载的方式上。 以下是调试问题和让代码工作的逐步指南:

1. 分析网站和按钮行为:

  • 了解按钮的类型:

    • 简单的 HTML 按钮或链接: 的当前选择器 ( '.styles_desktop_button__container__BMM1C > button:nth-child(1)' ) 应该可以正常工作。
    • 用 JavaScript 加载的按钮: 按钮可能在初始页面加载后被动态添加到 DOM 中。 在这种情况下,需要等待它出现。
    • 触发 JavaScript 函数的按钮: 点击按钮可能会触发修改 DOM 而不是直接链接到新页面的 JavaScript 函数。
  • 使用浏览器的开发者工具(在 Chrome 中为 Ctrl+Shift+C 或 Cmd+Opt+C):

    • 检查按钮元素: 确认正在使用正确的选择器,并且按钮在页面源代码中可见。
    • 监视网络请求: 点击按钮并查看它是否会触发任何 XHR 或提取请求。 这可以帮助了解按钮行为。

2. 调整 Splash Lua 脚本:

  • 处理动态加载的按钮: 如果按钮是动态加载的,请在尝试选择它之前使用 splash:wait_for_element lua splash:wait_for_element('.styles_desktop_button__container__BMM1C > button:nth-child(1)', timeout=10) -- 等待最多 10 秒 local button = splash:select('.styles_desktop_button__container__BMM1C > button:nth-child(1)')

  • 处理 JavaScript 操作: 如果按钮触发 JavaScript 函数,可能需要直接使用 splash:evaljs 执行该函数: lua local button_function = splash:evaljs("document.querySelector('.styles_desktop_button__container__BMM1C > button:nth-child(1)').onclick") splash:evaljs(button_function)

    • 注意: 需要调整 document.querySelector 以匹配按钮的实际 JavaScript 代码,该代码可能与用于选择它的 CSS 选择器不同。
  • 增加等待时间: 在点击按钮后增加 splash:wait() 时间可能会有所帮助,尤其是在网站加载内容缓慢的情况下: lua splash:wait(10) -- 等待 10 秒

3. 验证 Scrapy 代码:

  • 检查错误: 密切注意 Scrapy 日志中的任何错误消息。
  • 打印值: 使用 print() 语句在关键点打印值,例如选择器找到的按钮、响应状态和提取的图像 URL。

调试技巧:

  • 简化的代码: 从一个最小的示例开始,仅包含加载页面和点击按钮的代码。
  • 逐步执行: 一次添加一小段代码,以隔离问题。
  • 使用调试器: 使用调试器(如 Python 的 pdb 或 Lua 的调试器)逐步执行的代码。

通过仔细分析网站行为、调整 Splash Lua 脚本并使用调试技巧,应该能够识别并解决阻止按钮点击成功的问题。

标签:python,web-scraping,scrapy,scrapy-splash
From: 78810341

相关文章

  • 避免字符串连接的嵌套循环的 Pythonic 方法
    我想找到所有5位数字的字符串,其中前三位数字在我的第一个列表中,第二个槽第四个数字在我的第二个列表中,第三到第五个数字在我的最后一个列表中:l0=["123","567","451"]l1=["234","239","881"]l2=["348","551","399"......
  • Python 环境配置(二)安装jupyter、matplotlib、numpy库
    Python环境配置(二)安装jupyter、matplotlib、numpy库一、numpypipinstallnumpy二、matplotlibpipinstallmatplotlib三、jupyter1、anaconda自带Jupyter2、pycharm插件只有Pycharm的Professional版才支持JupyterNotebook,请注意版本3、新建文件#%......
  • 如何使用 PIPE 并行运行 python 子进程?
    我正在使用inkscape将一堆SVG图像转换为PNG。单线程:importsubprocessimporttimeimportosinkscape_path=r'C:\ProgramFiles\Inkscape\bin\inkscape.com'steps=30filenames=[]processes=[]#t_start=time.process_time()t_start=time.time()f......
  • Python sqlite3 删除数据
    要从SQLite表中删除记录,你需要使用DELETEFROM语句。要删除特定的记录,你需要同时使用WHERE子句。要更新特定的记录,你需要同时使用WHERE子句。语法以下是SQLite中DELETE查询的语法- DELETEFROMtable_name[WHEREClause]PythonCopy例子假设我们使用以下查询创建了......
  • Python 环境配置(一)Python、Anaconda、Pycharm的安装
    Python环境配置(一)Python、Anaconda、Pycharm的安装本人之前已安装一次,此次为卸载之后的重新安装。。。一、Python1、下载下载官网:下载链接:DownloadPython|Python.org勾选添加到路径(环境变量)next如图所示之后点close关闭2、验证win+Rcmd:python退出ex......
  • Pycharm 设置 yaml 格式接口测试用例模板 (python+pytest+yaml)
    前言初次编写的伙伴们可能对yaml格式不太熟悉,自己写yaml用例的时候,总是格式对不齐啊记不住设定好的关键字啊等等等琐事是我们可以在pycharm上设置用例模块,通过快捷方式调用出对应的模块,达到高效写用例的目的。 pycharm操作集:1、File-Settings(快捷键Ctrl+Alt+S) 2、Live......
  • Python - Redirecting output of print to a file
    Theprintfunctioncanalsobeusedtowritetoafile.Theoutputofprint,thatisbydefault,senttothescreencanberedirectedtoanopenfile.Forthis,youhavetosupplythefileobjectasanargumentforthenamedparameterfile.Hereisanexa......
  • Python:添加到相对于当前运行脚本的 sys.path 的最佳方法
    我有一个充满脚本的目录(比如说project/bin)。我还有一个位于project/lib的库,并希望脚本自动加载它。这是我通常在每个脚本的顶部使用的:#!/usr/bin/pythonfromos.pathimportdirname,realpath,sep,pardirimportsyssys.path.append(dirname(realpath(_......
  • python身份证号码+姓名一致性核验、身份证号码真伪查询API集成
    身份证号码+姓名核验的方式,顾名思义是身份证二要素核验,一般情况下,身份证真伪查询需要上公安户籍系统查询,但此种方式仅适合个人查询,企业要想随时随地实现身份证实名认证的功能,便需要集成身份证实名认证接口功能。翔云人工智能开放平台提供身份证号实名认证接口,实时联网,上传身份证......
  • 如何将数字分配给返回的 python 数据列表,我可以调用这些数据来打印
    这里完全是菜鸟。我在网上搜索过,找不到我想要做的事情的答案。我的代码在这里:importbs4asbsimporturllib.requestsauce=urllib.request.urlopen('https://www.amazon.com/gp/rss/bestsellers/kitchen/289851/ref=zg_bs_289851_rsslink').read()soup=bs.Beautiful......