使用Selenium Python查找下一个标签

0 投票
1 回答
1399 浏览
提问于 2025-04-21 01:00

简单来说,我正在使用Selenium来处理这个网页:http://www.registrar.ucla.edu/schedule/catalog.aspx?sa=APPLING&funsel=3。我创建了一个驱动程序,现在我在寻找一些符合特定条件的粗体文本。下面是我用来搜索粗体文本并找到匹配项的代码的一部分:

# Finds all bold matches which contain the class title 
    bold_matches = driver.find_elements_by_class_name('bold')
    class_title = ''
    class_description = ''
    for bold_match in bold_matches:
        # If the class title matches, we set our class title
        if bold_match.text[:bold_match.text.find('.')] == class_number:
            class_title = bold_match.text

你不需要太担心代码的细节,主要是当我们找到一个匹配的文本元素时,我们会把这个文本设置为课程标题。

我需要用Selenium做的事情是获取匹配文本的下一个标签。也就是说,我需要找到紧跟在匹配的bold_match后面的那个标签。这个下一个标签里包含的文本会用来设置class_description的内容。

我查阅了一些类似的问题,但它们都提到用xpath匹配id。这个网页的问题在于,粗体文本的标签和它后面的标签都没有任何id。

1 个回答

0

我找到了一种比较简单的方法来实现我需要的功能。下面是我的代码:

# Finds all bold matches which contain the class title 
bold_matches = driver.find_elements_by_class_name('bold')
class_title = ''
class_description = ''
for bold_match in bold_matches:
    # If the class title matches, we set our class title
    if bold_match.text[:bold_match.text.find('.')] == class_number:
        class_title = bold_match.text

        # We find the class description from the class title
        all_elements = driver.find_elements_by_xpath('//*')
        matching_index = all_elements.index(bold_match) + 2
        class_description = all_elements[matching_index].text

我发现我可以先找到我当前匹配的元素在 all_elements 列表中的位置,然后再找到下一个对应的位置来获取 class_description

撰写回答