beautifulsoup获取子节点
时间: 2023-10-30 15:06:14 浏览: 213
使用BeautifulSoup可以很方便地获取子节点。两种常用的方法如下:
1. 使用`find()`或`find_all()`方法获取父节点,然后使用`.`或`find()`方法获取子节点。
```python
from bs4 import BeautifulSoup
html = '''
<div class="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
'''
soup = BeautifulSoup(html, 'html.parser')
parent = soup.find('div', class_='parent')
children = parent.find_all('div', class_='child')
for child in children:
print(child.text)
```
输出:
```
Child 1
Child 2
Child 3
```
2. 直接使用`.`或`find()`方法获取子节点。
```python
from bs4 import BeautifulSoup
html = '''
<div class="parent">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
</div>
'''
soup = BeautifulSoup(html, 'html.parser')
children = soup.select('.parent .child')
for child in children:
print(child.text)
```
输出:
```
Child 1
Child 2
Child 3
```
第二种方法使用了CSS选择器,可以更加灵活地获取子节点。
阅读全文