2017-04-24 109 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属性值内。

相关问题