Example
Paragraph 1
Important Paragraph
Paragraph 3
可以尝试使用Beautiful Soup的find_all方法,或者对findAll方法添加更多的参数以精确匹配需要的标签和属性。例如,可以使用正则表达式模糊匹配属性名称,或使用CSS选择器语法进行更加复杂的选择。示例代码如下:
from bs4 import BeautifulSoup
import re
html = '''
Beautiful Soup Demo
Example
Paragraph 1
Important Paragraph
Paragraph 3
'''
# 使用find_all方法查找所有p标签
soup = BeautifulSoup(html, 'html.parser')
p_list = soup.find_all('p')
print(p_list)
# 使用正则表达式模糊匹配属性名称
p_list = soup.findAll('p', {'class': re.compile('.*port.*')})
print(p_list)
# 使用CSS选择器语法进行复杂选择
p_list = soup.select('div.content p:nth-of-type(odd)')
print(p_list)
输出结果为:
[Paragraph 1
, Important Paragraph
, Paragraph 3
]
[Important Paragraph
]
[Paragraph 1
, Paragraph 3
]