I am looking for a way to get the content of an element named "data-testid" from a website. This element exists about 35 times in different contexts with different content in the HTML code. The one that I am looking for goes like [data-testid="############-follow"], where ######## is a changing number. I am using Excel VBA with Selenium in order to work with the Chrome browser. The code is relatively simple and is mostly working, but I can't get this particular content. I open a webpage, look for elements with this name, and then scan all found elements if they contain the word "follow". Once found, I would extract the number before this word and store it in an Excel worksheet.
Set d = New ChromeDriver
d.Start "Chrome"
Set Rng = Range(Worksheets("followers").Range("A2"), Worksheets("followers").Range("A2").End(xlDown))
For Each Cell In Rng
If Cells(Cell.Row, 2).Value2 = "" Then
user = Cell.Value2
user = Replace(user, "@", "", 1, 1) 'remove "@"
d.Get "https://twitter.com/" & user 'navigate to user's page.
Set Result = d.FindElementsByXPath("//div[@data-testid]")
If Result.Count > 0 Then
For i = 1 To Result.Count
n = InStr(Result(i).Text, "-follow")
If n > 0 Then Exit For
Next
Cells(Cell.Row, 2).Value2 = Left(Result(i).Text, n - 1)
End If
End If
Next
This is the part of the HTML containing the desired element at the end:
<div role="button" data-focusable="true" tabindex="0" class="css-18t94o4 css-1dbjc4n r-1niwhzg r-p1n3y5 r-sdzlij r-1phboty r-rs99b7 r-1w2pmg r-1vuscfd r-1dhvaqw r-1ny4l3l r-1fneopy r-o7ynqc r-6416eg r-lrvibr" data-testid="1197328651785789440-follow">
Each item of the result [Result(1...35)] lists 4 boolean properties and one string type when I inspect it, the string is invariably the tag name "div". There is no other property shown. By chance, I tried the property "Text" [Result(i).Text] and it gives some text from the page, but none of the 35 elements shows the expected content.
As I have little experience with Selenium I would need help to understand how I can extract the content of this element Thanks