我正在使用 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.html
。 Selenium
在 Locating 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/