如何用selenium和python选择所有标签

时间:2015-05-11 19:14:41

标签: python selenium xpath selenium-webdriver

<a title="Citrate of Magnesia for Consumers" href="/cdi/citrate-of-magnesia-solution.html">
<b>Citrate of Magnesia</b>

我正在尝试从药物网站提取数据,如何选择<b></b>标签中的所有文字?因为那是我想要的文字。

我已经尝试*//a[@b]但它不起作用。

1 个答案:

答案 0 :(得分:2)

假设您尝试依赖前面的a元素,请使用following-sibling,例如:

//a/following-sibling::b

Python代码:

b = driver.find_element_by_xpath("//a/following-sibling::b")
print(b.text)

如果您想要多个b标记a作为前一个元素:

for b in driver.find_elements_by_xpath("//a/following-sibling::b"):
    print(b.text)

聊天后提供解决方案:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("http://www.drugs.com/drug-class/laxatives.html?condition_id=&generic=0&sort=rating&order=desc") 

# wait for the table list to load
table = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "table.data-list")))

for b in table.find_elements_by_css_selector("tr td > a[href] > b"):
    print(b.text)