怎样编写简易爬虫脚本

wen 实用脚本 25

本文目录导读:

怎样编写简易爬虫脚本

  1. 方法一:使用requests + BeautifulSoup(最常用)
  2. 方法二:简单完整的爬虫示例
  3. 方法三:使用Scrapy框架(更强大)
  4. 方法四:处理JavaScript渲染的页面
  5. 最简单的入门模板

我来教你编写一个简单实用的爬虫脚本,我会从最基础的方法开始,逐步介绍更强大的工具。

使用requests + BeautifulSoup(最常用)

import requests
from bs4 import BeautifulSoup
# 1. 发送请求获取网页内容
url = "https://example.com"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get(url, headers=headers)
# 2. 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 3. 提取数据 - 示例:获取所有标题s = soup.find_all('h2')  # 查找所有h2标签in titles:
    print(title.text.strip())
# 或者更精确地提取
# 查找class为"article-title"的元素
articles = soup.select('.article-title')
for article in articles:
    print(article.get_text())

简单完整的爬虫示例

import requests
from bs4 import BeautifulSoup
import csv
def simple_crawler(url, output_file='data.csv'):
    """
    简单的爬虫函数
    """
    # 设置请求头,模拟浏览器
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    try:
        # 发送请求
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查请求是否成功
        # 解析HTML
        soup = BeautifulSoup(response.text, 'html.parser')
        # 提取数据(根据实际网页结构调整)
        data = []
        # 示例:提取所有链接
        for link in soup.find_all('a'):
            href = link.get('href')
            text = link.text.strip()
            if href and text:  # 只保存有文本和链接的
                data.append([text, href])
        # 保存到CSV
        with open(output_file, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['文本', '链接'])
            writer.writerows(data)
        print(f"成功抓取 {len(data)} 条数据")
        return data
    except Exception as e:
        print(f"爬取失败: {e}")
        return []
# 使用示例
if __name__ == "__main__":
    url = "https://example.com"
    results = simple_crawler(url)

使用Scrapy框架(更强大)

首先安装:pip install scrapy

# 文件: my_spider.py
import scrapy
class MySpider(scrapy.Spider):
    name = "my_spider"
    start_urls = ['https://example.com']
    def parse(self, response):
        # 提取数据
        for item in response.css('div.article'):
            yield {
                'title': item.css('h2::text').get(),
                'link': item.css('a::attr(href)').get()
            }
        # 分页处理
        next_page = response.css('a.next::attr(href)').get()
        if next_page:
            yield response.follow(next_page, self.parse)

处理JavaScript渲染的页面

# 使用Selenium处理动态页面
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
def crawl_dynamic_page(url):
    # 创建浏览器驱动
    driver = webdriver.Chrome()  # 需要安装chromedriver
    try:
        driver.get(url)
        sleep(3)  # 等待页面加载
        # 提取数据
        elements = driver.find_elements(By.CLASS_NAME, "target-class")
        for element in elements:
            print(element.text)
    finally:
        driver.quit()

反爬虫应对

# 添加随机延迟
import time
import random
time.sleep(random.uniform(1, 3))  # 随机等待1-3秒
# 使用代理
proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}
response = requests.get(url, proxies=proxies)

异常处理

from retry import retry
@retry(tries=3, delay=2)
def fetch_url(url):
    response = requests.get(url, timeout=5)
    response.raise_for_status()
    return response

最好遵守的规范

  • 查看网站的 robots.txt 了解爬取限制
  • 设置合理的请求间隔
  • 不要过度请求,避免给服务器造成压力
  • 遵守网站的使用条款

安装必要的库

pip install requests beautifulsoup4 lxml scrapy selenium

最简单的入门模板

import requests
from bs4 import BeautifulSoup
# 三步完成基本爬虫
url = input("请输入要爬取的网址: ")
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 打印所有段落文本
for p in soup.find_all('p'):
    print(p.text)

这个脚本只有4行核心代码,适合初学者快速上手,实际使用时,请根据目标网站的结构调整解析逻辑。

抱歉,评论功能暂时关闭!