2017-07-27 35 views
1

問題是關於Python的CSS選擇器。無法創建合適的CSS選擇器

我不能用正確的方式編寫選擇器來選擇帶有「Last」的項目。我試着用:

div.pager a:[text*='Last'] 

元素在決定該項目位於:

<div class="pager"><a href="/search/1080p/" class="current">1</a> <a href="/search/1080p/t-23/">23</a> <a href="/search/1080p/t-255/">Last</a> </div> 
+1

我不認爲這是可能的只是CSS。 [這裏](https://stackoverflow.com/questions/5441680/css-selector-based-on-element-text)是一篇文章談論它。 –

+0

不幸的是,不可能爲某些文本創建選擇器(請參閱https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text)。但是,你可以通過執行'.pager a:last-child'來實現你想要的功能嗎? – joshhunt

+0

[有沒有包含特定文本的元素的CSS選擇器?](https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text) – Hans

回答

2

這絕對是可能的答案是:

div.pager a:contains("Last") 

而且,這裏是python腳本中使用的選擇:

import requests 
from lxml import html 

main_link = "https://www.yify-torrent.org/search/1080p/" 
base_link = "https://www.yify-torrent.org" 

def get_links(item_link): 
    response = requests.get(item_link).text 
    tree = html.fromstring(response) 
    next_page = tree.cssselect('div.pager a:contains("Next")')[0].attrib["href"] 
    last_page = tree.cssselect('div.pager a:contains("Last")')[0].attrib["href"] 
    print(base_link + next_page," ",base_link + last_page) 

get_links(main_link) 

結果:

https://www.yify-torrent.org/search/1080p/t-2/ 
https://www.yify-torrent.org/search/1080p/t-255/ 
+0

它不可能使用CSS,你可以使用jquery的方式。 – pacanga

+0

你讓我錯了。我用它作爲python腳本中的css選擇器。 – SIM

+0

然後請編輯您的文章,提供一些相關細節,並添加標籤。或者我會編輯它^^) – pacanga

1

你不能用[text*='blabla']選擇項目。您只能使用屬性來選擇它們。

但無論如何,如果你想選擇最後一個,你可以使用:last-of-typelast-child