python爬虫6个经典常用案例(完整代码)


Python 爬虫是一种强大的工具,可以用来从网页中提取数据。以下是六个常用的 Python 爬虫案例,涵盖了从简单的网页抓取到更复杂的动态内容抓取。

1. 抓取静态网页内容

目标:抓取一个静态网页的内容,并提取其中的特定信息。

示例:抓取一个新闻网站的标题和链接。

import requests
from bs4 import BeautifulSoup
 
url = 'https://news.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
 
# 提取标题和链接
for article in soup.find_all('article'):
    title = article.find('h2').text
    link = article.find('a')['href']
    print(f'Title: {
      
      title}\nLink: {
      
      link}\n')

2. 抓取多个网页(分页)

目标:抓取一个分页网站的所有页面内容。

示例:抓取一个分页的博客文章列表。

import requests
from bs4 import BeautifulSoup
 
base_url = 'https://blog.example.com/page/'
num_pages = 5
 
for page_num in range(1, num_pages + 1):
    url = f'{
      
      base_url}{
      
      page_num}'
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    
    for article in soup.find_all('article'):
        title = article.find('h2').text
        link = article.find('a')['href']
        print(f'Page {
      
      page_num}: Title: {
      
      title}\nLink: {
      
      link}\n')

3. 使用正则表达式提取数据

目标:使用正则表达式从网页中提取特定格式的数据。

示例:抓取一个网页中的电子邮件地址。

import requests
import re
 
url = 'https://contact.example.com'
response = requests.get(url)
content = response.text
 
# 使用正则表达式提取电子邮件地址
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', content)
for email in emails:
    print(email)

4. 处理动态内容(使用 Selenium)

目标:抓取使用 JavaScript 动态加载内容的网页。

示例:抓取一个使用 AJAX 加载数据的网页。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
 
# 设置 Chrome WebDriver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
 
url = 'https://dynamic.example.com'
driver.get(url)
 
# 等待动态内容加载完成
# 假设有一个特定的元素在内容加载完成后出现
element = driver.wait_for_element_present(By.ID, 'dynamic-content-id')
 
# 提取数据
content = driver.page_source
# 使用 BeautifulSoup 或其他方法解析内容
 
# 关闭浏览器
driver.quit()

5. 抓取带有登录认证的网页

目标:抓取需要登录认证的网页内容。

示例:抓取一个需要登录的仪表盘数据。

import requests
from requests.auth import HTTPBasicAuth
 
url = 'https://dashboard.example.com/data'
username = 'your_username'
password = 'your_password'
 
response = requests.get(url, auth=HTTPBasicAuth(username, password))
if response.status_code == 200:
    data = response.json()  # 假设返回的是 JSON 格式的数据
    print(data)
else:
    print('登录失败')

6. 使用 Scrapy 框架

目标:使用 Scrapy 框架进行大规模网页抓取。

示例:创建一个简单的 Scrapy 项目来抓取一个网站的数据。

# 安装 Scrapy
pip install scrapy
 
# 创建 Scrapy 项目
scrapy startproject myproject
 
# 创建爬虫
cd myproject
scrapy genspider myspider example.com
 
# 编辑 myproject/myspider/myspider.py
import scrapy
 
class MySpider(scrapy.Spider):
    name = 'myspider'
    allowed_domains = ['example.com']
    start_urls = ['https://example.com']
 
    def parse(self, response):
        for article in response.css('article'):
            title = article.css('h2::text').get()
            link = article.css('a::attr(href)').get()
            yield {
    
    
                'title': title,
                'link': link,
            }


 
# 运行爬虫
scrapy crawl myspider -o output.json

这些案例展示了 Python爬虫在不同场景下的应用,从简单的静态网页抓取到复杂的动态内容抓取和大规模数据抓取。希望这些示例能帮助你们更好地理解和使用 Python 爬虫技术。

猜你喜欢

转载自blog.csdn.net/2401_89383448/article/details/144932347
今日推荐