BeautifulSoup 定位标签及其输入属性

BeautifulSoup targeting label and its input attributes

我正在尝试使用 BeautifulSoup 提取 label class="checkbox"input data-filter-name="topics" 的项目的文本。

最终结果应该打印出位于此处的 13 个主题: https://www.pythondiscord.com/resources/

主题应该是:

我已经走到这一步了,但我不确定如何将标签和输入组合到 soup.find_all() 中以便仅针对上面的 13 个。我在下面定位的输入没有要输出的文本,所以我很确定我需要一些条件格式和/或函数来完成此操作。

page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')

topics = soup.find_all('input', {"data-filter-name": "topics"})

for i in range(0, len(topics)):
    print(topics[i].text)

这里是有问题的 HTML 的屏幕截图:

有几种方法可以做到这一点,但您应该尝试使用 css 选择器:

targets = soup.select('label.checkbox input[data-filter-name="topics"]')
for target in targets:
    print(target['data-filter-item'])

输出:

algorithms-and-data-structures
data-science
databases
discord-bots
game-development
general
microcontrollers
software-design
testing
tooling
user-interface
web-development
other