【问题标题】:Selenium Missing text valueSelenium 缺少文本值
【发布时间】:2021-08-25 07:48:40
【问题描述】:

我正在使用 python & beautifulsoup 来提取数据,但由于某种原因它没有看到文本值。

HTML 页面有:

<div ng-if="!order.hidePrices" style="white-space: nowrap;" class="ng-binding ng-scope">$ 1,599.00</div>

Python 代码:

for price in prices:
    price_value = price.find('div', {"class":"ng-binding", "class":"ng-scope"})
    print(price_value) 

而python输出缺少文本值:

<div class="ng-binding ng-scope" ng-if="!order.hidePrices" style="white-space: nowrap;"></div>

HTML 文件没有其他同名的类。我哪里做错了?

【问题讨论】:

    标签: python selenium selenium-chromedriver


    【解决方案1】:

    这里有几个问题:

    1. 您的定位器似乎不是唯一的。
    2. price_value 这是一个网络元素。要检索它的文本,您应该在其上应用.text
    3. 您在这里使用的是 BS,而不是 Selenium。

    看看这是否可行

    for price in prices:
        price_value = price.find('div', {"class":"ng-binding", "class":"ng-scope"})
        print(price_value.get_text()) 
    

    【讨论】:

      【解决方案2】:

      如果您有一个正在运行的驱动程序实例,请执行以下操作:

      print(driver.find_element_by_css_selector("div.ng-binding.ng-scope"").text)
      

      Selenium 不支持带空格的类名,因此请尝试使用 css 选择器。

      更新:

      for div in soup.select('div.ng-binding.ng-scope'):
          print(div.text)
      

      你也可以这样做:

      print(soup.find_all(attrs={'class': 'ng-binding'}, {'class': 'ng-scope'}))
      

      更新 1:

      请参阅here 官方文档所说的内容。

      html.parser 优点

      Batteries included
      
      Decent speed
      
      Lenient (As of Python 2.7.3 and 3.2.)
      

      html.parser 缺点

      Not as fast as lxml, less lenient than html5lib.
      

      阅读here for more detailed docs

      HTMLParser 实例被提供 HTML 数据并调用处理程序方法 开始标签、结束标签、文本、cmets 和其他标记元素是 遭遇。用户应该继承 HTMLParser 并覆盖它的 实现所需行为的方法。

      【讨论】:

      • 太棒了!这可行,但如果我使用 BeautifulSoup,我们该怎么做?
      • 我认为你可以做print(price_value.text) 应该可以帮助你解决这个问题。
      • '''print(price_value.text)''' 它返回空白
      • 用BS获取元素文本的方法是.get_text()看我的回答...
      • 你也可以像上面一样使用find_all来匹配它,试试看告诉我。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 2019-08-05
      • 2018-10-16
      相关资源
      最近更新 更多