爬虫的示范

import time
import requests
from bs4 import BeautifulSoup
import re
import csv
 
 
def get_links(url):
    # 发送GET请求并获取页面内容
    response = requests.get(url)
    # 解析HTML
    soup = BeautifulSoup(response.text, 'html.parser')
    # 提取所有链接
    links = []
    for link in soup.find_all('a'):
        href = link.get('href')
        if href and href.startswith('http'):
            links.append(href)
            save_data(href, "", f"data_url.csv")
 
    return links
 
 
def scrape_data(url):
    # 发送GET请求获取网页内容
    response = requests.get(url)
    # 获取网页内容的编码
    # encoding = response.encoding
    encoding = 'gbk'
    # 解析网页内容
    soup = BeautifulSoup(response.text, 'html.parser')
    # 剔除标签并获取文本内容
    text = soup.get_text()
    # 去除多余的空格和换行符
    text = re.sub(r'\s+', ' ', text).strip()
    # 解码unicode字符
    decoded_text = text.encode(encoding, errors='ignore').decode(encoding)
    return decoded_text
 
 
def save_data(url, data, filename):
    with open(filename, 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([url, data])  # 写入数据行
    print(f"保存成功: {filename}")
 
 
def crawl(start_url, depth=2):
    visited = set()  # 存储已访问的链接
    queue = [(start_url, 0)]  # 使用队列实现广度优先搜索,同时记录深度
 
    while queue:
        url, level = queue.pop(0)  # 从队列中取出一个链接
        if level > depth:  # 达到指定深度则停止
            break
        try:
            if url not in visited:
                visited.add(url)
                print(f"正在爬取: {url}")
                # 爬取数据
                data = scrape_data(url)
                # 保存数据
                save_data(url, data, f"data_{level}.csv")
                # 获取链接
                links = get_links(url)
                # 将链接添加到队列中
                queue.extend([(link, level + 1) for link in links])
            # time.sleep(1)
        except Exception as e:
            print(f"发生异常: {str(e)},跳过链接: {url}")
            continue
 
 
start_url = 'https://www.ferrari.com/zh-CN/news'
crawl(start_url, depth=2)

### 回答1: 以下是一个简单的 Python 爬虫程序示范: ```python import requests from bs4 import BeautifulSoup url = 'https://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') for link in soup.find_all('a'): print(link.get('href')) ``` 这个程序使用 requests 库发送 HTTP 请求,然后使用 BeautifulSoup 库解析 HTML 页面,最后打印出页面中所有链接的 URL。 ### 回答2: 以下是一个简单的爬虫程序示范: ```python import requests from bs4 import BeautifulSoup # 首先发送 HTTP 请求获取网页内容 response = requests.get("https://example.com") # 使用 BeautifulSoup 解析网页内容 soup = BeautifulSoup(response.text, "html.parser") # 查找网页中的特定元素 titles = soup.find_all("h1") # 查找所有的 h1 标签 # 打印标题 for title in titles: print(title.text) # 查找网页中的链接 links = soup.find_all("a") # 查找所有的链接 # 打印链接 for link in links: print(link.get("href")) # 将爬到的数据保存到文件 with open("output.txt", "w", encoding="utf-8") as file: for title in titles: file.write(title.text + "\n") ``` 以上是一个基本的爬虫程序示范,它使用了 Python 的 requests 库来发送 HTTP 请求,使用 BeautifulSoup 库来解析网页内容,并使用一些简单的操作来提取所需的数据。示范中的程序发送了一个 GET 请求到示例网页(https://example.com),然后使用 BeautifulSoup 解析网页内容并找到其中的 h1 标签和链接,并将它们打印出来和保存到文件中。通过这个简单示范,您可以了解到使用爬虫程序获取网页内容和提取数据的基本步骤和方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值