【问题标题】:Xpath: obtain href if contains specific wordXpath:如果包含特定单词,则获取href
【发布时间】:2017-09-20 22:50:52
【问题描述】:

设置

我正在使用以下 xpath 从页面中提取 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']


问题

我对@9​​87654323@ href 不感兴趣。我感兴趣的所有href都包含Glasgow。如何仅选择包含 Glasgow 的 href?

我已经看到了有关'id' 等正则表达式的答案,但没有看到href。这些答案似乎不适用于href。

我已经看到有关带有 href 开头或结尾的正则表达式的答案,但我希望能够在“包含”一个单词时进行正则表达式。

【问题讨论】:

  • 试试'/html/body/div/div[2]/div[2]/div/div/p[1]/a[contains(@href, "Glasgow")]/@href'
  • @WiktorStribiżew:谢谢!我将您的'Glasgow' 调整为"Glasgow",然后它起作用了。使用 '' 我在 Scrapy Shell 中遇到语法错误。
  • 是的,我注意到用于定义字符串文字的单引号,并在您的评论出现前一秒更改了我的评论。我在下面发布了答案。
  • 看到了!我会接受的。

标签: python regex xpath href


【解决方案1】:

a 元素上使用contains(@href, 'Glasgow')“限制”:

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

然后,它只会查找指定路径下的那些<a>s,在它们的href属性值中包含Glasgow

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 2018-03-12
    • 2016-03-23
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多