python实现爬虫例子2

网络爬虫是一个可以自动抓取互联网内容的程序。Python有很多库可以用来实现网络爬虫,其中最常用的是requests(用于发送HTTP请求)和BeautifulSoup(用于解析HTML)。

以下是一个简单的Python网络爬虫示例,该爬虫会抓取指定网页的所有标题(<title>标签)并打印出来:

import requests  
from bs4 import BeautifulSoup  
  
def get_titles(url):  
    # 发送HTTP请求  
    response = requests.get(url)  
      
    # 检查请求是否成功  
    if response.status_code != 200:  
        print(f"Failed to retrieve the webpage. Status code: {response.status_code}")  
        return []  
      
    # 解析HTML内容  
    soup = BeautifulSoup(response.text, 'html.parser')  
      
    # 查找所有的<title>标签  
    titles = soup.find_all('title')  
      
    # 提取并返回标题文本  
    return [title.text for title in titles]  
  
# 使用示例  
url = 'https://www.exam.....pl....e.com'  # 替换为你想要爬取的网页URL  
titles = get_titles(url)  
for title in titles:  
    print(title)

相关推荐

  1. python实现爬虫例子2

    2024-04-25 05:52:06       27 阅读
  2. python实现数据爬虫

    2024-04-25 05:52:06       42 阅读
  3. python实现网络爬虫

    2024-04-25 05:52:06       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-25 05:52:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-25 05:52:06       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-25 05:52:06       82 阅读
  4. Python语言-面向对象

    2024-04-25 05:52:06       91 阅读

热门阅读

  1. 十八、QGIS的作用和下载

    2024-04-25 05:52:06       38 阅读
  2. pandas保存dict字段再读取成DataFrame

    2024-04-25 05:52:06       32 阅读
  3. springboot针对thymeleaf的使用总结

    2024-04-25 05:52:06       35 阅读
  4. [Android]使用CompositionLocal隐式传值

    2024-04-25 05:52:06       28 阅读
  5. 前端获取资源的方式(ajax、fetch)及其区别

    2024-04-25 05:52:06       37 阅读