【问题标题】:How to implement following-sibling axis of xpath alternative in Beautifulsoup Python如何在 Beautifulsoup Python 中实现 xpath 替代的跟随兄弟轴
【发布时间】:2015-11-20 12:20:36
【问题描述】:

我正在尝试使用 Bs4、selenium 和 Python 收集文本我想使用以下方法获取文本 "Lisa Staprans"

name = str(profilePageSource.find(class_="hzi-font hzi-Man-Outline").div.get_text().encode("utf-8"))[2:-1]

代码如下:

<div class="profile-about-right">
 <div class="text-bold">
  SF Peninsula Interior Design Firm
  <br/>
  Best of Houzz 2015
 </div>
 <br/>
 <div class="page-tags" style="display:none">
  page_type: pro_plus_profile
 </div>
 <div class="pro-info-horizontal-list text-m text-dt-s">
  <div class="info-list-label">
   <i class="hzi-font hzi-Ruler">
   </i>
   <div class="info-list-text">
    <span class="hide" itemscope="" itemtype="http://data-vocabulary.org/Breadcr
umb">
     <a href="http://www.houzz.com/professionals/c/Menlo-Park--CA" itemprop="url
">
      <span itemprop="title">
       Professionals
      </span>
     </a>
    </span>
    <span itemprop="child" itemscope="" itemtype="http://data-vocabulary.org/Bre
adcrumb">
     <a href="http://www.houzz.com/professionals/interior-designer/c/Menlo-Park-
-CA" itemprop="url">
      <span itemprop="title">
       Interior Designers &amp; Decorators
      </span>
     </a>
    </span>
   </div>
  </div>
  <div class="info-list-label">
   <i class="hzi-font hzi-Man-Outline">
   </i>
   <div class="info-list-text">
    <b>
     Contact
    </b>
    : Lisa Staprans
   </div>
  </div>
 </div>
</div>

请告诉我情况如何。

【问题讨论】:

  • hzi-font hzi-Man-Outline 没有孩子,所以你走错路了
  • 是的,请告诉我如何选择第二个 class="info-list-text"
  • 我实际上是在使用 webdriver 使用 selenium 的方式,但我认为应该使用:find(class_="info-list-text").get_text()(或者innerHtml),然后你使用`:`
  • print(profilePageSource.find_all('div', {'class': "info-list-text"})[1].text)?另外,你想用 selenium 还是 bs4 来做这个?

标签: python selenium beautifulsoup


【解决方案1】:

我假设您使用的是 Beautifulsoup,因为您使用的是 class_ 属性字典- 如果有一个类名为hzi-font hzi-Man-Outlinediv,那么试试-

str(profilePageSource.find(class_="hzi-font hzi-Man-Outline").findNext('div').get_text().split(":")[-1]).strip()

提取'Lisa Staprans'

这里 findNext 导航到下一个 div 并提取文本。

【讨论】:

    【解决方案2】:

    我现在无法测试它,但我会这样做:

    profilePageSource.find_element_by_class_name("info-list-text").get_attribute('innerHTML')
    

    那么您将不得不考虑: 来拆分结果(如果总是这样的话)。

    欲了解更多信息:https://selenium-python.readthedocs.org/en/latest/navigating.html

    【讨论】:

      【解决方案3】:

      这部分可能有问题:

      find(class_="hzi-font hzi-Man-Outline")
      

      获取正确信息的一种简单方法是:通过使用谷歌浏览器检查页面源中您需要的元素,右键单击它,复制元素的 xpath,然后使用:

      profilePageSource.find_element_by_xpath(<xpath copied from Chorme>).text
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多