正在Scrapy中跳过HTML标记

ruyhziif  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(130)

我正在使用Scrapy(Python3)从一个网站上抓取数据,我想跳过源代码中的一个标记,因为有两个标记,而且它们都有相同的类,如下图所示:

我正在尝试选择以蓝色突出显示的标记。
我用这个:response.xpath("//nav[@class='mp-PaginationControls-pagination']/a/@href").get(),但这只让我选择第一个标签,所以在我进入第二页后它会出错。
下面是原始XML:

<div class="mp-PaginationControls mp-PaginationControls--new">
  <nav class="mp-PaginationControls-pagination">
    <a class="mp-TextLink mp-Button mp-Button--primary" href="/l/muziek-en-instrumenten/microfoons/">
      <span aria-hidden="true" class="mp-Button-icon mp-Button-icon--center mp-svg-arrow-left--inverse"></span>
    </a>
    <span class="mp-PaginationControls-pagination-pageList">
      <a class="mp-TextLink" href="/l/muziek-en-instrumenten/microfoons/">1</a>
      <span>2</span>
      <a class="mp-TextLink" href="/l/muziek-en-instrumenten/microfoons/p/3/">3</a>
      <span>...</span>
      <span>142</span>
    </span>
    <span class="mp-PaginationControls-pagination-amountOfPages">Pagina 2 van 142</span>
    <a class="mp-TextLink mp-Button mp-Button--primary" href="/l/muziek-en-instrumenten/microfoons/p/3/">
      <span aria-hidden="true" class="mp-Button-icon mp-Button-icon--center mp-svg-arrow-right--inverse"></span>
    </a>
  </nav>
</div>

先谢谢你

qmb5sa22

qmb5sa221#

正如我从您共享的XML中看到的,第二个a具有不同的href属性值。
但是,既然您想获得它的href值,我想您不能基于它来构建XPath ...
但是在a的下面是span节点,所以你可以根据它找到父节点a
如下所示:

response.xpath("//nav[@class='mp-PaginationControls-pagination']//a[./span[contains(@class,'mp-svg-arrow-right--inverse')]]/@href").get()

相关问题