python使用beautifulsoup解析网页,获取指定标签的子元素列表

可以使用BeautifulSoup的find_all方法获取指定标签的子元素列表。 示例代码如下:

```
from bs4 import BeautifulSoup
import requests

url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 获取所有的<a>标签
a_tags = soup.find_all('a')

# 遍历<a>标签列表,输出每个<a>标签的文本内容和链接属性
for a in a_tags:
    print(a.text, a['href'])
```

在上面的示例代码中,我们首先使用requests库获取指定网页的html代码,然后将其传入BeautifulSoup对象。通过调用对象的find_all方法,我们可以一次性获取html中所有的指定标签的子元素列表,例如获取所有的`<a>`标签,之后遍历列表,输出每个标签的文本内容和链接属性。

相关代码参考