要在命令行界面中运行Beautiful Soup,您需要首先安装Beautiful Soup库。可以使用以下命令在命令行中安装Beautiful Soup:
pip install beautifulsoup4
然后,您可以创建一个Python脚本文件(例如bs_example.py
),并在其中导入Beautiful Soup库并使用它。以下是一个示例代码:
from bs4 import BeautifulSoup
html_doc = """
Example
Beautiful Soup Example
This is a paragraph.
- Item 1
- Item 2
- Item 3
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 打印标题
print(soup.title.text)
# 打印第一个段落
print(soup.p.text)
# 打印无序列表中的所有项目
for li in soup.ul.find_all('li'):
print(li.text)
您可以在命令行中运行此脚本,并查看输出结果。例如,使用以下命令:
python bs_example.py
将会输出:
Example
This is a paragraph.
Item 1
Item 2
Item 3
请注意,您需要确保已经正确安装了Python和Beautiful Soup库。