【问题标题】:Need help on extracting data using Xpath in my Python code在我的 Python 代码中使用 Xpath 提取数据需要帮助
【发布时间】:2012-01-23 20:16:00
【问题描述】:

问题 1

这是 HTML 代码。

<div class="preferredContact paragraph">ph:<span preferredcontact="40">(02) 9540 9959</span></div> 

我正在尝试使用 xpath 提取该电话号码。

我试过了

data['phone'] = c.xpath('.//span[@preferredContact="40"]/text()')

data['phone'] = c.xpath('.//span[contains(@preferredContact,"40")]/text()')

它们都只返回null。谁能告诉我提取该电话号码的代码吗?

问题 2

HTML代码是

<a rel="nofollow" title="View website for Ruth Newman Architect (in new window)" target="_blank" name="listing_website" id="websiteLink40" alreadysentorpevent="false" class="links ext-no-tooltip orpDuplicateEvent" href="/app/redirect?headingCode=27898&amp;productId=473639214&amp;productVersion=1&amp;listingUrl=%2Fnsw%2Fgymea-bay%2Fruth-newman-architect-12781682-listing.html&amp;webSite=http%3A%2F%2Fwww.ruthnewman.com.au&amp;pt=w&amp;context=businessTypeSearch&amp;referredBy=YOL&amp;eventType=websiteReferral">www.ruthnewman.com.au
</a>

我想获取位于字符串 webSite=http%3A%2F%2F 旁边的链接。此字符串在 href 属性的值中。所以,在上面的例子中,我想要 www.ruthnewman.com.au。我不知道如何使用 Xpath 来获得它。

有人可以帮忙吗?

【问题讨论】:

  • 拼写错误:“preferredcontact”与“preferredContact”。
  • 嘿,谢谢,成功了!对第二个问题有帮助吗?
  • 一开始我想我误解了第二个问题。如果我编辑的答案解决了这个问题,请告诉我。

标签: xpath screen-scraping


【解决方案1】:

属性区分大小写。第一个问题使用(无大写):

.//span[@preferredcontact='40']/text()

第二个问题使用:

substring-before(substring-after(
    .//a[contains(@href, 'webSite=')]/@href, 'webSite=http%3A%2F%2F'), '&')

这首先选择属性中的所有之后 'webSite=http%3A%2F%2F',然后,使用它作为substring-before的输入,提取所有之前第一个&amp;,其中应该包含目标字符串。

请注意,在您给定的示例中,descendant-or-self (//) 轴并不是真正需要的。尽量避免它。获得的灵活性是以精度和效率为代价的。

【讨论】:

  • 我不知道为什么,但是substring-before(substring-after( .//a[contains(@href, 'webSite=')]/@href, 'webSite=http%3A%2F%2F'), '&amp;') 抛出了无效的语法错误。
猜你喜欢
  • 2019-11-07
  • 2021-09-05
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多