Selenium如何定位所有带有标签h2的元素

ffscu2ro  于 2023-01-26  发布在  其他
关注(0)|答案(2)|浏览(201)

你好,所以鉴于我已经导航到这个网站
https://uk.trustpilot.com/categories
我想使用inspect元素检索每个类别的标题,我注意到每个类别的标题都有一个h2标记

我的想法是使用一个EC条件来等待所有具有h2标记的元素的可见性,这将返回一个包含所有h2标记的列表,然后我可以调用getattribute(text)来获取文本

def select_catogory(self):
        list = self.wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, 'h2')))
        print(len(list))
        catogories = self.driver.find_elements(By.TAG_NAME,value ="h2")
        for cat in catogories:
            print(cat.get_attribute('text')

所有元素的presence_of_all_elements_located均未返回任何内容,并且与find_elements相同

我意识到我的主要问题是在我的循环中,我从来没有一个中断条件,所以它给出了一个陈旧的元素警告,我认为这是由这个函数引起的,谢谢帮助

def select_button_by_name(self, name_of_button: str):
        """
        Navigates to the button in question and clicks on it

        input: name_of_button (string)
        """
        self.wait
       
        buttons_by_href = self.driver.find_elements(By.XPATH,value ="//a[@href]") #finds all the href tags on the webpage
        for button in buttons_by_href:
           # Matches the attribute text to the provided button string
            if button.get_attribute("text") == name_of_button:
                #clicks on the button
                button.click()
                break
frebpwbc

frebpwbc1#

SeleniumBase解决方案行之有效:
pip install seleniumbase,然后运行pythonpytest

from seleniumbase import BaseCase
BaseCase.main(__name__, __file__, "-s")

class MyTestClass(BaseCase):
    def test_base(self):
        self.open("https://uk.trustpilot.com/categories")
        h2_elements = self.find_visible_elements("h2")
        print()
        for element in h2_elements:
            print(element.text.strip())

输出为:

Animals & Pets
Beauty & Well-being
Business Services
Construction & Manufacturing
Education & Training
Electronics & Technology
Events & Entertainment
Food, Beverages & Tobacco
Health & Medical
Hobbies & Crafts
Home & Garden
Home Services
Legal Services & Government
Media & Publishing
Money & Insurance
Public & Local Services
Restaurants & Bars
Shopping & Fashion
Sports
Travel & Vacation
Utilities
Vehicles & Transportation
2izufjch

2izufjch2#

您可以在一行代码中使用Seleniumpython来提取每个类别的标题,从而将WebDriverWait归纳为visibility_of_all_elements_located(),并且可以使用以下Locator Strategies之一:

  • 使用 * CSS选择器 * 和get_attribute("textContent")
driver.get('https://uk.trustpilot.com/categories')
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#onetrust-accept-btn-handler"))).click()
print([my_elem.get_attribute("textContent") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "h2[class^='typography_heading']")))])
  • 使用 * XPATH * 和 * text * 属性:
driver.get('https://uk.trustpilot.com/categories')
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#onetrust-accept-btn-handler"))).click()
print([my_elem.text for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//h2[text()]")))])
  • 控制台输出:
['Animals & Pets', 'Beauty & Well-being', 'Business Services', 'Construction & Manufacturing', 'Education & Training', 'Electronics & Technology', 'Events & Entertainment', 'Food, Beverages & Tobacco', 'Health & Medical', 'Hobbies & Crafts', 'Home & Garden', 'Home Services', 'Legal Services & Government', 'Media & Publishing', 'Money & Insurance', 'Public & Local Services', 'Restaurants & Bars', 'Shopping & Fashion', 'Sports', 'Travel & Vacation', 'Utilities', 'Vehicles & Transportation']
      • 注意**:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

相关问题