python 网络爬虫
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                
import requests
from bs4 import BeautifulSoup
 
def get_html(url):
    """
    获取网页HTML内容
    :param url: 网页的URL
    :return: HTML内容
    """
    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):
    """
    解析HTML内容,提取有效信息
    :param html: 网页HTML内容
    :return: 提取的信息列表
    """
    soup = BeautifulSoup(html, 'html.parser')
    # 假设我们要提取所有的段落文本
    paragraphs = soup.find_all('p')
    return [p.get_text() for p in paragraphs]
 
def main():
    url = 'http://example.com'  # 替换为你要爬取的网页URL
    html = get_html(url)
    if html:
        parsed_info = parse_html(html)
        for info in parsed_info:
            print(info)
    else:
        print('Failed to retrieve HTML content')
 
if __name__ == '__main__':
    main()这个简单的Python网络爬虫示例展示了如何使用requests库获取网页内容,并使用BeautifulSoup库解析HTML。在这个例子中,我们假设我们要提取所有段落标签<p>中的文本。这个例子需要进一步细化和功能扩展才能适应实际的爬虫项目,但它是学习爬虫编写的一个很好的起点。
评论已关闭