当前位置:首页 > Python > 正文

Python网页爬取与解析完全教程 | 从入门到实践

Python网页爬取与解析完全教程

一、网页爬取基础

网页爬取是指通过程序自动从互联网获取网页内容的过程。在Python中,我们通常使用requests库来实现这一功能。

1.1 安装requests库

pip install requests

1.2 发送HTTP请求

import requests

# 发送GET请求
response = requests.get('https://example.com')

# 检查请求是否成功
if response.status_code == 200:
    print('请求成功!')
    html_content = response.text
else:
    print(f'请求失败,状态码: {response.status_code}')

二、HTML解析技术

获取HTML内容后,我们需要解析文档结构来提取有用信息。BeautifulSoup是最常用的HTML解析库。

2.1 安装BeautifulSoup

pip install beautifulsoup4

2.2 解析HTML文档

from bs4 import BeautifulSoup

# 创建BeautifulSoup对象
soup = BeautifulSoup(html_content, 'html.parser')

# 提取页面标题
page_title = soup.title.string
print(f'页面标题: {page_title}')

# 查找所有链接
links = soup.find_all('a')
for link in links:
    print(link.get('href'))

三、CSS选择器使用

BeautifulSoup支持使用CSS选择器定位元素,这是最常用的元素定位方式。

3.1 基本选择器

# 选择所有段落
paragraphs = soup.select('p')

# 选择特定class的元素
special_items = soup.select('.special-class')

# 选择特定id的元素
header = soup.select('#main-header')

3.2 复杂选择器

# 选择直接子元素
children = soup.select('div > p')

# 选择相邻兄弟元素
siblings = soup.select('h2 + p')

# 选择属性符合要求的元素
images = soup.select('img[src^="https://"]')

四、实际爬取案例

下面是一个完整的爬取示例,获取书籍信息:

import requests
from bs4 import BeautifulSoup

def scrape_books():
    url = 'https://books.toscrape.com/'
    response = requests.get(url)
    
    if response.status_code != 200:
        print("无法获取网页内容")
        return
    
    soup = BeautifulSoup(response.text, 'html.parser')
    books = []
    
    # 提取所有书籍信息
    for article in soup.select('article.product_pod'):
        title = article.h3.a['title']
        price = article.select('p.price_color')[0].get_text()
        rating = article.p['class'][1]  # 例如: Three, Four, Five
        
        books.append({
            'title': title,
            'price': price,
            'rating': rating
        })
    
    # 打印前5本书籍
    for book in books[:5]:
        print(f"标题: {book['title']}")
        print(f"价格: {book['price']}")
        print(f"评分: {book['rating']}星")
        print('-' * 50)

if __name__ == "__main__":
    scrape_books()

五、爬虫最佳实践

5.1 设置请求头

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept-Language': 'zh-CN,zh;q=0.9'
}

response = requests.get('https://example.com', headers=headers)

5.2 处理异常

try:
    response = requests.get('https://example.com', timeout=10)
    response.raise_for_status()  # 检查HTTP错误
except requests.exceptions.RequestException as e:
    print(f"请求发生错误: {e}")

5.3 遵守robots.txt

在爬取任何网站前,检查其robots.txt文件:

import requests
from urllib.robotparser import RobotFileParser

rp = RobotFileParser()
rp.set_url('https://example.com/robots.txt')
rp.read()

if rp.can_fetch('MyBot', 'https://example.com/some-page'):
    print("允许爬取")
else:
    print("禁止爬取")

六、处理动态内容

对于JavaScript渲染的内容,可以使用Selenium或Playwright:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# 设置无头浏览器
options = webdriver.ChromeOptions()
options.add_argument('--headless')

# 初始化浏览器
driver = webdriver.Chrome(
    service=Service(ChromeDriverManager().install()),
    options=options
)

# 访问页面
driver.get('https://example.com')

# 获取渲染后的HTML
html_content = driver.page_source

# 关闭浏览器
driver.quit()

# 使用BeautifulSoup解析
soup = BeautifulSoup(html_content, 'html.parser')
# 后续解析代码...

七、总结

网页爬取与解析是数据获取的重要技术,Python提供了强大的工具链:

  • requests - 发送HTTP请求
  • BeautifulSoup - 解析HTML/XML文档
  • Selenium/Playwright - 处理JavaScript渲染页面

实际应用中,请务必遵守目标网站的爬取规则,尊重robots.txt,设置合理的请求间隔,避免对目标网站造成过大压力。

发表评论