【问题标题】:Selenium - How to jump from one sibling to otherSelenium - 如何从一个兄弟姐妹跳到另一个兄弟姐妹
【发布时间】:2014-07-12 22:46:25
【问题描述】:

我正在使用 Selenium-Python 来抓取此链接上的内容。 http://targetstudy.com/school/62292/universal-academy/

HTML代码是这样的,

<tr>
  <td>
    <i class="fa fa-mobile">
      ::before
    </i>
  </td>
  <td>8349992220, 8349992221</td>
 </tr>

我不知道如何使用 class="fa fa-mobile" 获取手机号码 有人可以帮忙吗。谢谢

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import time
    from selenium.webdriver.common.action_chains import ActionChains
    import lxml.html
    from selenium.common.exceptions import NoSuchElementException

    path_to_chromedriver = 'chromedriver.exe'
    browser = webdriver.Chrome(executable_path = path_to_chromedriver)
    browser.get('http://targetstudy.com/school/62292/universal-academy/')
    stuff = browser.page_source.encode('ascii', 'ignore')
    tree = lxml.html.fromstring(stuff)
    address1 = tree.xpath('//td/i[@class="fa fa-mobile"]/parent/following-sibling/following-sibling::text()')

    print address1

【问题讨论】:

    标签: python selenium lxml lxml.html


    【解决方案1】:

    您不需要lxml.htmlSeleniumLocating Elements 中很强大。

    //i[@class="fa fa-mobile"]/../following-sibling::td xpath 表达式传递给find_element_by_xpath()

    >>> from selenium import webdriver
    >>> browser = webdriver.Firefox()
    >>> browser.get('http://targetstudy.com/school/62292/universal-academy/')
    >>> browser.find_element_by_xpath('//i[@class="fa fa-mobile"]/../following-sibling::td').text
    u'83499*****, 83499*****'
    

    注意,加了*,因为这里没有显示实数。

    这里xpath首先定位i标签与fa fa-mobile类,然后去父并获取下一个td兄弟元素。

    希望对您有所帮助。

    【讨论】:

    • 我认为你没有回答这个问题。您的代码只返回以下同级,如果后面还有更多呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2020-05-27
    • 2021-01-30
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多