python - Selenium - 如何从一个 sibling 跳转到另一个 sibling

标签 python selenium lxml lxml.html

我正在使用 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

最佳答案

为此,您不需要 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 首先找到带有 fa fa-mobile 类的 i 标记,然后转到父级并获取下一个 td 同级元素。

希望有帮助。

关于python - Selenium - 如何从一个 sibling 跳转到另一个 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23831525/

相关文章:

java - 运行 firefox 时出现 selenium 错误

selenium - 什么可能导致 UnhandledAlertException 错误?

python - 在 Fedora 上运行 python 脚本时没有名为 lxml.html 的模块

Python Requests 拆分 TCP 数据包

python - 加速 Kronecker 产品 Numpy

selenium - 使用 Protractor 定位链接的最佳方法

python - 使用 LXML xml 设置没有值的属性

python - 将 C 中的包含文件转换为 python

python - 组合三个正则表达式