我正在尝试抓取文本:
Eligible for free shipping with Amazon Prime
关于 All Offers this product页面使用以下 XPath:
.//*[@id='olpOfferList']/div/div/div[2]/div[1]/span[2]/i/span[contains(@class, '-')]
.//*[@id='olpOfferList']/div/div/div[2]/div[1]/span[2]/i/span
但是,尽管两个 XPath 在 Firebug 中都匹配,但它们在 Selenium 中返回一个空字符串。
我大致使用以下代码来抓取文本:
try {
String scrapedText = driver.findElement(By.xpath(XPath)).getText();
} catch (Exception e) {
e.printStackTrace();
}
编辑:由于某种原因,stackoverflow 上的链接没有重定向到“所有优惠”页面(仅到主产品页面)。要查看“所有优惠”页面上的 HTML,请附加以下内容:
/gp/offer-listing/0615797806/ref=olp_f_new?ie=UTF8&f_all=true&f_new=true to amazon.com
更新:以下是页面中的 HTML 片段。
<div class="a-fixed-left-flipped-grid a-spacing-mini">
<div class="a-fixed-left-grid-inner" style="padding-left:170px">
<div id="olpOfferListColumn" class="a-fixed-left-grid-col a-col-right" style="padding-left:0%;width:100%;float:right;">
<div id="olpOfferList" class="a-section olpOfferList">
<div class="a-section a-padding-small">
<div class="a-section a-spacing-double-large" role="grid" aria-readonly="true" aria-label="More buying choices">
<div class="a-row a-spacing-mini" role="row">
<hr class="a-spacing-mini a-divider-normal"/>
<div class="a-row a-spacing-mini olpOffer" role="row">
<div class="a-column a-span2 olpPriceColumn" role="gridcell">
<span class="a-size-large a-color-price olpOfferPrice a-text-bold"> $10.79 </span>
<span class="supersaver">
<i class="a-icon a-icon-prime" aria-label="Eligible for free shipping with Amazon Prime.">
<span class="a-icon-alt">Eligible for free shipping with Amazon Prime.</span> // I want to scrape this text
</i>
</span>
<p class="olpShippingInfo">
</div>
<div class="a-column a-span3 olpConditionColumn" role="gridcell">
<div class="a-column a-span3 olpDeliveryColumn" role="gridcell">
<div class="a-column a-span2 olpSellerColumn" role="gridcell">
<div class="a-column a-span2 olpBuyColumn a-span-last" role="gridcell">
</div>
最佳答案
我将尝试用“完成工作”的方式来回答我自己的问题,但我仍在寻找更好的答案。
如果不是通过 getText()
进行抓取,而是通过 getAttribute()
使用属性 "textContent"
进行抓取,我能够成功抓取上述内容。
但是,尽管这项技术回答了问题(或解决了根本问题),但我仍在寻找一种直接使用 getText()
方法来执行此操作的方法,因此我认为这只是部分答案。我还试图理解为什么我的原始代码不起作用。
关于java - 无法通过 XPath 和 WebDriver 抓取 Span 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49736369/