Python 网页采集代码示例:获取网站信息

以下是一个简单的 Python 网页采集代码示例,可用于获取特定网站上的信息:

import requests
from bs4 import BeautifulSoup

# 发送请求,获取数据
url = 'http://example.com'
response = requests.get(url)
html = response.text

# 解析数据,提取所需信息
 soup = BeautifulSoup(html, 'html.parser')
title = soup.find('title').text
links = [link.get('href') for link in soup.find_all('a')]

# 输出结果
print('Title:', title)
print('Links:', links)

说明:

  1. 导入 requestsBeautifulSoup 库。
  2. 发送请求获取网页源代码。
  3. 使用 BeautifulSoup 库解析 HTML,提取所需信息。
  4. 输出结果。

需要注意的是,该示例代码只是一个基础框架,具体采集过程中需要根据具体情况进行调整和优化。例如,需要添加异常处理、设置请求头、使用代理等。


原文地址: https://www.cveoy.top/t/topic/mmx8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录