从零开始的 Python 爬虫速成指南_从零 爬虫一个网站
    		       		warning:
    		            这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
    		        
        		                
                
import requests
from bs4 import BeautifulSoup
 
# 初始化爬虫的URL
url = 'https://example.com'
 
# 发送HTTP请求
response = requests.get(url)
 
# 检查请求是否成功
if response.status_code == 200:
    # 解析响应内容
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 打印网页的标题
    print(soup.title.text)
    
    # 提取所有的段落
    paragraphs = soup.find_all('p')
    for p in paragraphs:
        print(p.text)
else:
    print(f"请求失败,状态码: {response.status_code}")这段代码使用了requests库来发送HTTP GET请求,使用了BeautifulSoup库来解析HTML内容。代码首先检查请求是否成功,如果成功,它会打印网页的标题和所有段落的文本内容。如果请求失败,它会打印状态码。这是学习爬虫的基本步骤之一。
评论已关闭