Python爬虫代码示例:使用requests和beautifulsoup4抓取网页数据
这是一个简单的Python爬虫代码示例,使用'requests'和'beautifulsoup4'库来抓取网页数据:
import requests
from bs4 import BeautifulSoup
# 定义目标URL
url = 'http://example.com'
# 发送HTTP GET请求
response = requests.get(url)
# 检查响应状态码
if response.status_code == 200:
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(response.content, 'html.parser')
# 进行必要的网页数据提取操作
# 这里只是一个示例,您可以根据需求进行相应的处理
# 获取页面标题
title = soup.title.string
print('页面标题:', title)
# 获取所有链接
links = soup.find_all('a')
print('所有链接:')
for link in links:
print(link.get('href'))
else:
print('请求失败,状态码:', response.status_code)
请注意,这只是一个简单的示例,实际的爬虫代码需要根据具体的需求和网站结构进行定制。另外,请确保您在爬取网页数据时遵守相关网站的使用条款和隐私政策。
原文地址: https://www.cveoy.top/t/topic/bEiv 著作权归作者所有。请勿转载和采集!