以下是一个简单的 Python 爬虫示例,可以爬取指定网站中的文字信息,并将其输出到控制台上:

import requests
from bs4 import BeautifulSoup

url = 'https://www.example.com' # 替换为你要爬取的网站地址

response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

# 查找所有的文本信息
text_list = []
for text in soup.find_all(text=True):
    if text.parent.name not in ['style', 'script', 'head', 'title', 'meta', '[document]']:  
        text_list.append(text)

# 输出文本信息
for text in text_list:
    print(text.strip())

解释:

  1. 导入所需的库:requests 用于获取网页内容,BeautifulSoup 用于解析网页内容。
  2. 定义要爬取的网站地址。
  3. 通过 requests 库获取网页内容,并用 BeautifulSoup 解析网页内容。
  4. 查找所有的文本信息,并将其存储到一个列表中。
  5. 遍历文本信息列表,并输出每个文本信息。
Python 爬虫教程:如何提取网站文字信息

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

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