如果没有“下一个错误恢复",则无法执行我的代码; [英] Can't execute my code without "on error resume next"

查看:28
本文介绍了如果没有“下一个错误恢复",则无法执行我的代码;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 VBA 中结合 selenium 编写一个爬虫来解析网页上不同产品的价格,我在执行时遇到问题.当它发现某些价格不存在时,它就会中断.使用下一个错误恢复"我可以获得完整的结果.但是,我希望在不使用on error resume next"的情况下执行我的代码.如果不是硒,我可以使用 Length 属性来摆脱它.但是,硒不支持这一点.希望我可以在这里找到任何解决方法.

Writing a crawler in VBA in combination with selenium to parse the price of different products from a webpage, I get an issue upon execution. It breaks when it finds certain prices are none. Using "on error resume next" I can get the full results. However, I wish to execute my code without using "on error resume next". If it were not for selenium, I could have used Length property to get rid of that. But, selenium doesn't support that. Hope I can have any workaround here.

Sub Redmart_scraping()
Dim driver As New ChromeDriver
Dim posts As Object, post As Object

With driver
    .get "https://redmart.com/bakery"
    Set posts = .FindElementsByCss("li.productPreview")
End With

On Error Resume Next

For Each post In posts
    i = i + 1
    Cells(i, 1) = post.FindElementByCss("span[class^=ProductPrice__price]").Text
Next post
End Sub

推荐答案

您可以提取价格如下:

Sub Redmart_scraping()
Dim driver As New ChromeDriver
Dim posts As Object
Dim i As Long

With driver
    .get "https://redmart.com/bakery"
End With

Columns("A:A").NumberFormat = "[$$-409]#,##0.00"

For Each posts In driver.FindElementsByClass("productPreview")
    i = i + 1
    'Cells(i, 2) = posts.Text
    For Each Item In Split(posts.Text, vbLf)
        If InStr(1, Item, "$", vbTextCompare) > 0 Then
            If InStr(2, Item, "$", vbTextCompare) > 0 Then
                Cells(i, 1) = Mid(Item, 2, InStr(2, Item, "$", vbTextCompare) - 2)
            Else
                Cells(i, 1) = Right(Item, Len(Item) - 1)
            End If

       End If
    Next
Next
End Sub

请注意,posts.Text 包含您对一件商品所需的所有信息.因此,除了价格之外,您还可以提取商品名称、折扣、客户评分、重量、折扣前价格和保证新鲜日期.. 取消注释 'Cells(i, 2) = posts.Text 并亲自查看.

Please note that posts.Text holds all the information you need for one item. So besides price, you can extract item name, discount, customer ratings, weight, price before discount, and guaranteed fresh dates.. Uncomment 'Cells(i, 2) = posts.Text and see for yourself.

我将剩下的有趣工作留给您.祝你好运!

I am leaving rest of the fun work to you. Good luck!

这篇关于如果没有“下一个错误恢复",则无法执行我的代码;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆