0Pricing
Web Scraping & Bots · Урок

Использование Requests для URL

Научитесь отправлять запросы GET и POST для получения содержимого веб-страниц с помощью библиотеки Requests в Python.

«Использование Requests для URL» — бесплатный урок Web Scraping & Bots на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web Scraping & Bots, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web Scraping & Bots содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Meet Python's Requests Library

Добро пожаловать в мир использования Python для взаимодействия с веб-ресурсами! В этом уроке мы погрузимся в изучение библиотеки Requests — вашего основного инструмента для выполнения HTTP-запросов.

Requests упрощает процесс общения вашей программы на Python с веб-сайтами, действуя подобно веб-браузеру, но без графического интерфейса. Это незаменимый инструмент для получения содержимого веб-страниц, необходимого для последующего извлечения данных.

Setting Up Requests

Прежде чем мы сможем использовать Requests, нам нужно его установить. Если вы еще этого не сделали, откройте терминал или командную строку и выполните следующую команду:

pip install requests

Эта команда загружает и устанавливает библиотеку, делая ее доступной для ваших скриптов на Python. Это разовая настройка для вашего окружения.

Your First GET Request

Наиболее распространенным типом запроса является GET. Он используется для получения данных из указанного ресурса, подобно тому, как ваш браузер загружает веб-страницу.

Давайте выполним простой GET-запрос для получения контента с сайта example.com. Затем мы выведем HTTP-код состояния и фрагмент текста страницы.

import requests

# Define the URL you want to fetch
url = "http://www.example.com"

# Send a GET request
response = requests.get(url)

# Print the status code and first 200 characters of the content
print(f"Status Code: {response.status_code}")
print(f"Content snippet:\n{response.text[:200]}")

Understanding the Response Object

When you make a request, the requests.get() function returns a Response object. This object holds all the information about the server's reply.

  • response.status_code: An integer indicating the HTTP status (e.g., 200 for OK, 404 for Not Found).
  • response.text: The content of the response, usually HTML, as a string.
  • response.url: The actual URL of the response.

Basic Error Checking

It's good practice to check if your request was successful. The response.raise_for_status() method is a simple way to do this.

If the HTTP status code indicates an error (e.g., 4xx or 5xx), this method will raise an HTTPError. Otherwise, it does nothing.

import requests

url = "http://www.example.com/nonexistent-page"

try:
    response = requests.get(url)
    response.raise_for_status() # Raises an HTTPError for bad responses (4xx or 5xx)
    print("Request successful!")
except requests.exceptions.HTTPError as err:
    print(f"HTTP Error occurred: {err}")
except requests.exceptions.ConnectionError as err:
    print(f"Connection Error occurred: {err}")
except Exception as err:
    print(f"An unexpected error occurred: {err}")

Adding Request Headers

Sometimes, websites check for specific HTTP headers to determine if a request is coming from a legitimate browser or a bot.

You can customize your request by passing a dictionary of headers. A common header to set is User-Agent to mimic a browser.

import requests

url = "http://httpbin.org/get" # A service that echoes your request

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": "en-US,en;q=0.9"
}

response = requests.get(url, headers=headers)

print("Your request headers sent to httpbin.org:")
# httpbin.org returns JSON, so we can use .json()
print(response.json()['headers']['User-Agent'])
print(response.json()['headers']['Accept-Language'])

Understanding POST Requests

While GET requests are for retrieving data, POST requests are used to send data to a server, typically for creating or updating a resource.

Think of submitting a form on a website – you're usually sending data via a POST request. The data is included in the request body, not in the URL.

Sending Data with POST

To send a POST request with data, you use requests.post() and pass your data as a dictionary to the data parameter.

Let's try sending some simple form data to httpbin.org/post, which will echo back the data it received.

import requests

url = "http://httpbin.org/post"

# Data to send in the POST request
payload = {
    "name": "Coddy",
    "city": "Kitland",
    "age": "5"
}

response = requests.post(url, data=payload)

print("Data received by httpbin.org:")
# The 'form' key in the JSON response contains the sent data
print(response.json()['form'])

GET vs. POST: Key Differences

It's crucial to understand when to use GET versus POST:

  • GET: Retrieves data, parameters are visible in the URL, requests can be bookmarked and cached. Best for non-sensitive data retrieval.
  • POST: Sends data to be processed, parameters are in the request body (not visible in URL), requests are not cached or bookmarked. Best for submitting forms, uploading files, or sensitive data.

Check Your Understanding

You've learned about GET and POST requests. Consider the following scenario:

You want to retrieve the current weather forecast for a specific city from a public API. Which HTTP request method is most appropriate?

Lesson Summary

Great job! You've taken a significant step in understanding how to interact with the web using Python's Requests library.

  • We installed the requests library.
  • We learned to send GET requests to fetch web content.
  • We explored the response object, checking status codes and content.
  • We briefly touched on handling request errors.
  • We customized requests with headers.
  • We learned to send data using POST requests.
  • Finally, we distinguished between GET and POST for different web interactions.

Next, we'll learn how to parse the HTML content you've fetched!

Часто задаваемые вопросы

Урок «Использование Requests для URL» бесплатный?

Да — полный текст урока «Использование Requests для URL» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web Scraping & Bots, подпишись на CoddyKit PRO. Курс Web Scraping & Bots содержит 4 уроков всего.

Чему я научусь в уроке «Использование Requests для URL»?

Научитесь отправлять запросы GET и POST для получения содержимого веб-страниц с помощью библиотеки Requests в Python. Ты практикуешь Web Scraping & Bots с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Web Scraping & Bots?

Предыдущий опыт не требуется. Web Scraping & Bots на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Использование Requests для URL»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Web Scraping & Bots?

Да. Каждый урок Web Scraping & Bots включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Настройка среды
  2. Использование Requests для URL
  3. Извлечение данных с помощью BeautifulSoup
  4. Навигация по DOM с помощью CSS-селекторов
← Назад к Web Scraping & Bots