这是我要从中提取数据的网站链接,我试图href在锚标记下获取属性的所有文本。这是示例html:
href
<div id="borderForGrid" class="border"> <h5 class=""> <a href="/products/product-details/?prod=30AD">A/D TC-55 SEALER</a> </h5> <div id="borderForGrid" class="border"> <h5 class=""> <a href="/products/product-details/?prod=P380">Carbocrylic 3356-1</a> </h5>
我想提取所有文本值,例如['A/D TC-55 SEALER','Carbocrylic 3356-1']。 我尝试了:
['A/D TC-55 SEALER','Carbocrylic 3356-1']
target = driver.find_element_by_class_name('border') anchorElement = target.find_element_by_tag_name('a') anchorElement.text
但它给出''(空)字符串。
''
关于如何实现的任何建议?
PS-在“ 产品类型”* 下选择单选按钮的第一个值 *
要提取<a>标签内的所有文本值,例如 [‘A / D TC-55 SEALER’,’Carbocrylic 3356-1’] ,您必须为引入 WebDriverWait ,visibility_of_all_elements_located()并且可以使用以下任一解决方案:
<a>
visibility_of_all_elements_located()
使用CSS_SELECTOR:
CSS_SELECTOR
print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.topLevel[data-types='Acrylics'] h5>a[href^='/products/product-details/?prod=']")))])
使用XPATH:
XPATH
print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='topLevel' and @data-types='Acrylics']//h5[@class]/a[starts-with(@href, '/products/product-details/?prod=')]")))])
注意 :您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC