【问题标题】:Getting meta tags from a page source using Selenium Python使用 Selenium Python 从页面源获取元标记
【发布时间】:2013-10-04 04:20:32
【问题描述】:

我正在尝试从 URL https://play.google.com/store/apps/details?id=com.teslacoilsw.launcher&hl=en 获取数据并获取以下数据

   <meta content="3.99" itemprop="price"> 

我使用以下在 Python 中实现的代码来获取,但它失败了。

    browser = webdriver.Firefox() # Get local session of firefox
    browser.get(sampleURL) # Load page
    assert "Google Play" in browser.title
    priceValue = browser.find_element_by_xpath("//div[@itemprop='price']")#
    print priceValue.text

但它说它找不到价值价格的xpath。知道为什么吗?

编辑

priceValue = browser.find_element_by_xpath("//meta[@itemprop='price']")
print priceValue.text

我得到空字符串

【问题讨论】:

    标签: python firefox xpath selenium


    【解决方案1】:

    如果我查看页面源代码,例如 Chrome view-source:https://play.google.com/store/apps/details?id=com.teslacoilsw.launcher&amp;hl=en。我也没有找到具有@itemprop 属性和price 值的&lt;div&gt; 元素。

    所以你的 XPath 是完全错误的。 browser.find_element_by_xpath() 还返回一个元素,您想要提取 @content 的属性值。然后你应该使用下一个:

    priceValue = browser.find_element_by_xpath("//meta[@itemprop='price']")
    print priceValue.get_attribute("content")
    

    【讨论】:

    • 使用 firefox 时,您的建议出现以下错误:给定的选择器 //meta[@itemprop=\'price\']/@content 无效或不会生成 WebElement。发生以下错误:\nInvalidSelectorError: xpath 表达式“//meta[@itemprop=\'price\']/@content”的结果是:[object XrayWrapper [object Attr]]。它应该是一个元素。'
    • 那么值3.99 的XPath 将是//meta[@itemprop='price']/@content。如果您需要获取返回的元素而不是值,可以使用//meta[@itemprop='price']。这将返回 &lt;meta&gt; 元素
    • @SiddharthanAsokan 你不需要做print priceValue.text,但是你想要属性值还是不想要?然后你需要做print priceValue.get_attribute("content")。查看我的更正答案
    【解决方案2】:

    我认为这个解决方案效果很好。

    priceValue = browser.find_element_by_xpath("//div[@itemprop='price']")
    print(priceValue.text)
    

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 2022-01-26
      • 2016-01-13
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 2012-01-20
      相关资源
      最近更新 更多