如何使用Beautiful Soup打印指定父类下子类中的所有anchor标签
提取指定标签的实现方案
需求说明
打印class属性为brandGroup choose_a(id为brandGroup)的div元素下,所有class属性为brandChild的子div中的<a>标签。
HTML示例代码
<div id="brandGroup" class="brandGroup choose_a"> <div class="brandChild"><a href="abc.com">comments</a></div> <div class="brandChild"><a href="xyz.com">comments</a></div> <div class="brandChild"><a href="fgh.com">comments</a></div> <div>
尝试的代码
x=soup.find('div', id="brandGroup", class_="brandGroup choose_a").find_all('div',class_="brandChild") for i in x: print(i.find_all('a'))
优化实现方案
你当前的代码能获取到目标<a>标签,但find_all('a')会返回列表格式结果。如果想更灵活地打印标签内容或属性,可参考以下调整:
打印完整标签
# 定位目标父容器 parent_div = soup.find('div', id="brandGroup", class_="brandGroup choose_a") # 遍历所有子div并提取a标签 for child_div in parent_div.find_all('div', class_="brandChild"): a_tag = child_div.find('a') print(a_tag)
打印标签的文本内容
parent_div = soup.find('div', id="brandGroup", class_="brandGroup choose_a") for child_div in parent_div.find_all('div', class_="brandChild"): print(child_div.find('a').text)
打印标签的href属性
parent_div = soup.find('div', id="brandGroup", class_="brandGroup choose_a") for child_div in parent_div.find_all('div', class_="brandChild"): print(child_div.find('a')['href'])
也可以用CSS选择器一步简化代码:
for a_tag in soup.select('#brandGroup.brandGroup.choose_a div.brandChild a'): print(a_tag)
内容的提问来源于stack exchange,提问作者james
相关产品推荐
相关产品推荐

