如何使用VBA获取谷歌搜索的第一个搜索结果链接? [英] How to get the first search result link of a google search using VBA?

查看:33
本文介绍了如何使用VBA获取谷歌搜索的第一个搜索结果链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的日常任务中,我目前必须搜索大量产品并收集有关这些产品的信息.所以我的想法是在 google 上搜索产品,并通过从产品标题部分提取数据来从第一个搜索结果中获取信息,并且几乎对许多产品进行循环.

In my day to day tasks I currently have to search a large number of products and gather information on these products. So my idea is to search the product on google and get the info from the first search result by extracting the data from the product title section and pretty much loop this for a number of products.

到目前为止,这是我的代码:

Here is my code below so far:

Sub SkuAutomation()

Dim ie As Object


'Navigates to google
 Set ie = CreateObject("InternetExplorer.application")
 ie.Visible = True
 ie.Navigate "https://google.co.uk/search?q=" & Worksheets("sheet1").Cell(9, 4).Value & " " & Worksheets("sheet1").Cells(9, 2)


'Waits for page to load before next action

Do While ie.ReadyState <> READYSTATE_COMPLETE

Loop

End Sub

我只想添加一段代码,它要么点击谷歌返回的第一个链接,要么为我返回链接.我的想法是从该页面的产品标题部分抓取数据!不过还是非常早期的阶段.

I just want to add a piece of code which either clicks on the first link that google returns or returns the link for me. My idea would then to be scrape the data from the product title section from that page! still very early stages though.

我只是一个初学者,所以任何类型的帮助都将不胜感激!提前谢谢了.

I am just a beginner so any type of help would be much appreciated! Many thanks in advance.

推荐答案

您对此的看法可能会有所不同,但对于您提供的内容,您可以使用 CSS 选择器组合通过页面样式定位第一个链接.

Your mileage will likely vary on this but for what you have provided you can use a CSS selector combination to target the first link by the page styling.

我使用 #search div.r [href*=http] 但你可以简化为 #search .r a.不过,我很想知道 href 中有一个 http.

I use #search div.r [href*=http] but you could simplify to #search .r a. I am interested in knowing there is an http in the href though.

# 是一个 id 选择器,一个空格 " " 是一个后代选择器(选择前面元素的一个子元素和 []> 是一个属性选择器.一个 "." 是一个类选择器,即通过类名选择一个元素.

The # is an id selector, a space " " is a descendant selector (selects a child of the preceeding element and the [] is an attribute selector. A "." is a class selector i.e. selects an element by class name.

我正在寻找具有 href 属性的第一个元素,其值中包含 http,该元素的父元素 div 元素具有类名r,其父节点的 id 为 search.

I am looking for the first element with an href attribute containing http in its value that has a parent element div element with class name r, whose parent has an id of search.

Option Explicit
Public Sub GetLink()
    Dim ie As New InternetExplorer
    With ie
        .Visible = True
        .navigate "https://google.co.uk/search?q=Currys+241825"

        While .Busy Or .readyState < 4: DoEvents: Wend

        Debug.Print .document.querySelector("#search div.r [href*=http]").href

        .Quit
    End With

End Sub

这篇关于如何使用VBA获取谷歌搜索的第一个搜索结果链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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