Python 爬虫 基础教程
时间: 2025-02-24 11:38:30 浏览: 40
### Python Web Scraping Beginner Tutorial
For beginners interested in learning how to scrape websites using Python, understanding the basics of HTTP requests and HTML parsing is essential[^1]. Below is a simple example demonstrating how to perform web scraping with `requests` and `BeautifulSoup`.
#### Import Necessary Libraries
Firstly, install necessary libraries via pip or conda. Then import these packages into your script.
```python
import requests
from bs4 import BeautifulSoup
```
#### Send an HTTP Request
Use the `requests.get()` function to send GET requests to target URLs.
```python
url = 'http://example.com'
response = requests.get(url)
print(response.status_code) # Print status code; should be 200 indicating success.
```
#### Parse HTML Content
After obtaining webpage content through response.text, use BeautifulSoup for parsing.
```python
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.find('title').string
print(f'Title of the page: {title}')
```
#### Extract Data from Tags
Locate specific tags by their attributes such as id or class name.
```python
paragraphs = soup.find_all('p', {'class': 'special'})
for p in paragraphs:
print(p.get_text())
```
This basic guide covers fundamental operations involved when starting out with Python-based web scraping tools like Requests and Beautiful Soup.
阅读全文
相关推荐

















