Scrapy - 根据文本选择特定链接

hoo*_*ted 8 python web-crawler scrapy

这应该很容易,但我被卡住了.

<div class="paginationControl">
  <a href="/en/overview/0-All_manufactures/0-All_models.html?page=2&amp;powerunit=2">Link Text 2</a> | 
  <a href="/en/overview/0-All_manufactures/0-All_models.html?page=3&amp;powerunit=2">Link Text 3</a> | 
  <a href="/en/overview/0-All_manufactures/0-All_models.html?page=4&amp;powerunit=2">Link Text 4</a> | 
  <a href="/en/overview/0-All_manufactures/0-All_models.html?page=5&amp;powerunit=2">Link Text 5</a> |   

<!-- Next page link --> 
  <a href="/en/overview/0-All_manufactures/0-All_models.html?page=2&amp;powerunit=2">Link Text Next ></a>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用Scrapy(Basespider)根据它的链接文本选择链接:

nextPage = HtmlXPathSelector(response).select("//div[@class='paginationControl']/a/@href").re("(.+)*?Next")
Run Code Online (Sandbox Code Playgroud)

例如,我想根据它的文本是"链接文本下一步"的事实选择下一页链接.有任何想法吗?

unu*_*tbu 14

用途a[contains(text(),'Link Text Next')]:

nextPage = HtmlXPathSelector(response).select(
    "//div[@class='paginationControl']/a[contains(text(),'Link Text Next')]/@href")
Run Code Online (Sandbox Code Playgroud)

参考:XPath上的文档包含函数


PS.你的文字最后Link Text Next有一个空格.为了避免在代码中包含该空格:

text()="Link Text Next "
Run Code Online (Sandbox Code Playgroud)

我认为使用contains更具一般性,但仍然具体.


ice*_*ime 6

您可以使用以下 XPath 表达式:

//div[@class='paginationControl']/a[text()="Link Text Next"]/@href
Run Code Online (Sandbox Code Playgroud)

这将选择href带有文本的链接的属性"Link Text Next"

如果您需要更多控制,请参阅XPath 字符串函数