Search code examples
google-apps-scriptweb-scrapingcheerio

Scraping text() value if href contains a part of specific text


I'm trying to collect the text in a if href contains venue/, so I tried to do it this way:

var venue = $('.details > span > a:contains(href="venue/")');
sheet.getRange(3,17).setValue(venue.text().trim());

But returns with no value, how should I be able to retrieve such value?
As the site changes the positions of the elements from time to time, I need to define this contains.

Expected Result:

Estadio Manuel Ferreira (Asunción)

Map Example:

<div class="details ">
       <a href="/matches/2021/08/12/">11/08/2021</a>

       <span class="divider"></span>

       <a href="/international/south-america/copa-libertadores/2021/quarter-finals/r61990/">CONMEBOL Libertadores</a>

       <span class="divider"></span>


         <span>KO</span>
         <span>
           19:15
         </span>
      <br>
         <span>Venue</span>
         <span>
              <a href="venue/">Estadio Manuel Ferreira (Asunción)</a></span>
     </div>

Link to site:
https://int.soccerway.com/matches/2021/08/12/south-america/copa-libertadores/club-olimpia/clube-de-regatas-de-flamengo/3579565/


Solution

  • It seems like the issue is right on the first line, as the “venue” variable does not return what you expect.

    I propose you select the anchor you are looking for by getting the last element of type a in the div you provided and assign the value of its href attribute to a variable called venue. After that, check if the venue variable is equal to venue/. If the condition returns true, get the anchor’s inner text, assign it to a variable called result and log it.

    You can make it work by using the following code:

    let element = $('.details a').last()
    let venue = element.attr('href');
    
    if (venue === 'venue/') {
      let result = element.text()
      console.log(result) // this is the value you are looking for
    }
    

    Updated:

    let elements = $('.details a')
    
    elements.each((index, value) => {
        let href = $(value).attr('href')
        if (href === 'venue/') {
            console.log($(value).text())
        }
    })