2017-04-24 127 views
1

設置Xpath的:如果包含特定單詞

我使用以下XPath提取網頁的HREF獲得HREF,

'/html/body/div/div[2]/div[2]/div/div/p[1]/a/@href' 

,給了我HREF中的列表看起來像,

['#', 
'showv2.php?p=Glasgow City&t=Anderston', 
'showv2.php?p=Glasgow City&t=Anniesland', 
'showv2.php?p=Glasgow City&t=Ashfield', 
'#', 
'showv2.php?p=Glasgow City&t=Baillieston', 
      ⋮ 
'showv2.php?p=Glasgow City&t=Yoker'] 


問題

我對'#' hrefs沒有興趣。所有我感興趣的href包含Glasgow。如何只選擇包含Glasgow的hrefs?

我已經看到有關正則表達式與'id'等的答案,但沒有與href。這些答案似乎不適用於href。

我已經看到有關正則表達式與開始或結束的href的答案,但我想能夠包含一個單詞的正則表達式。

+0

嘗試'/ html/body/div/div [2]/div [2]/div/div/p [1]/a [contains(@href,「Glasgow」)]/@ href'' –

+0

@WiktorStribiżew:謝謝!我把你的格拉斯哥調到了格拉斯哥,然後它就起作用了。 '''我在Scrapy Shell中出現語法錯誤。 – LucSpan

+0

是的,我注意到用來定義字符串文字的單引號,並且在你出現之前改變了我的評論。我在下面發佈了一個答案。 –

回答

3

使用contains(@href, 'Glasgow')a元素「限購」:

'/html/body/div/div[2]/div[2]/div/div/p[1]/a[contains(@href, "Glasgow")]/@href' 

然後,它只會找到指定的路徑下的<a> s表示含有Glasgow他們href屬性值內。

相關問題