import requests
from bs4 import BeautifulSoup
 
def get_html(url):
    """发送HTTP请求,获取网页内容"""
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        else:
            return None
    except requests.RequestException:
        return None
 
def parse_html(html):
    """解析网页,提取有效信息"""
    soup = BeautifulSoup(html, 'html.parser')
    # 假设我们要提取所有的段落文本
    paragraphs = soup.find_all('p')
    return [p.get_text() for p in paragraphs]
 
def main():
    url = 'http://example.com'  # 替换为你要爬取的网页地址
    html = get_html(url)
    if html:
        paragraphs = parse_html(html)
        for p in paragraphs:
            print(p)
    else:
        print("Failed to retrieve the webpage content")
 
if __name__ == '__main__':
    main()这段代码展示了如何使用requests库获取网页内容,以及如何使用BeautifulSoup库解析HTML并提取所需信息。代码中的get_html函数负责发送HTTP请求,而parse_html函数负责解析HTML并提取文本。main函数则是程序的入口点,负责组织流程并调用其他函数。