Search code examples
xpathscrapy-shell

Parsing through response created with XPath


Using Scrapy, I want to extract some data from a HTML well-formed site. With XPath I am able to extract a list of items, but I am not able to extra data from the elements in the list, using XPath

All XPath's have been tested using XPather. I have tested the issue using a local file that contains the webpage, same issue.

Here goes:

# Get the webpage
fetch("https://www.someurl.com")

# The following gives me the expected items from the HTML
products = response.xpath("//*[@id='product-list-146620']/div/div")

The items are like this:

<div data-pageindex="1" data-guid="13157582" class="col ">
  <div class="item item-card item-card--static">
    <div class="item-card__inner">
      <div class="item__image item__image--overlay">
        <a href="/www.something.anywhere?ref_gr=9801" class="ratio_custom" style="padding-bottom:100%">
        </a>
      </div>
      <div class="item__text-container">
        <div class="item__name">
          <a class="item__name-link" href="/c.aspx?ref_gr=9801">The text I want</a>
        </div>
      </div>
    </div>
  </div>
</div>

When using the following Xpath to extract "The text I want", i dont get anything:

XPATH_PRODUCT_NAME = "/div/div/div/div/div[contains(@class,'item__name')]/a/text()"
products[0].xpath(XPATH_PRODUCT_NAME).extract()

The output is empty, why?


Solution

  • Try the following code.

    XPATH_PRODUCT_NAME = ".//div[@class='item__name']/a[@class='item__name-link']/text()"
    products[0].xpath(XPATH_PRODUCT_NAME).extract()