Python Достъп до Интернет чрез Urllib.Request и urlopen()
⚡ Умно обобщение
urllib is the standard Python модул за достъп до интернет данни, позволяващ отварянето на програми URLи извлича HTML, JSON или двоично съдържание. Функцията urllib.request.urlopen() се свързва с уеб адрес и чете отговора на сървъра директно в Python.

Разделите по-долу обясняват какво е urllib, как да отворите URL и да прочетете HTML кода му, както и как да се справяте с грешки, да изтегляте файлове и да избирате между urllib и библиотеката за заявки.
Какво е urllib?
urllib е a Python модул, който може да се използва за отваряне URLс. Той дефинира функции и класове, които помагат в URL действия.
с Python, you can also access and retrieve data from the internet, such as XML, HTML, and JSON, and then work with this data directly. In the sections below, we will see how to retrieve data from the web. For example, here we use a Guru99 видео URL, достъп до него чрез Python, and print the HTML file of this URL.
The urllib package groups several modules: urllib.request for opening URLs, urllib.error for the exceptions that requests can raise, urllib.parse for building and parsing URLs и urllib.robotparser за четене на robots.txt файлове.
Как да отворите URL използване на Urllib
Преди да изпълним кода за свързване с интернет данни, трябва да импортираме URL library module, or “urllib”.
- Импортиране на urllib
- Определете вашата основна функция
- Декларирайте променливата webUrl
- След това извикайте функцията urlopen в библиотеката urllib
- - URL отваряме е Guru99 урок по YouTube
- След това отпечатваме кода на резултата
- Резултатният код се извлича чрез извикване на функцията getcode на променливата webUrl, която сме създали.
- We convert that to a string, so that it can be concatenated with our string “result code”
- This will be a regular HTTP code “200”, indicating the HTTP request is processed successfully
Как да получите HTML файл от URL in Python
Можете също да прочетете HTML файла, като използвате функцията read() в PythonКогато изпълните кода, HTML файлът ще се появи в конзолата.
- Извикайте функцията read() на променливата webUrl
- The read() method allows you to read the contents of data files
- Прочетете цялото съдържание на URL в променлива, наречена данни
- Run the code and it will print the data in HTML format
Ето пълния код:
Python 2 Пример
# # read the data from the URL and print it # import urllib2 def main(): # open a connection to a URL using urllib2 webUrl = urllib2.urlopen("https://www.youtube.com/user/guru99com") #get the result code and print it print "result code: " + str(webUrl.getcode()) # read the data from the URL and print it data = webUrl.read() print data if __name__ == "__main__": main()
Python 3 Пример
# # read the data from the URL and print it # import urllib.request # open a connection to a URL using urllib webUrl = urllib.request.urlopen('https://www.youtube.com/user/guru99com') #get the result code and print it print ("result code: " + str(webUrl.getcode())) # read the data from the URL and print it data = webUrl.read() print (data)
How to Handle urllib Errors: URLГрешка и HTTP грешка
Заявката не винаги е успешна. Когато нещо се обърка, urllib повдига изключение вместо да връща данни, така че е важно да се обработват тези грешки. Модулът urllib.error дефинира два основни класа изключения.
- HTTPError се генерира, когато сървърът върне код за състояние на грешка, като например 404 Не е намерен или 500 Вътрешна грешка на сървъра. Той съдържа кода на състоянието и тялото на отговора.
- URLгрешка is raised when the server cannot be reached at all, for example because of a wrong domain name or no internet connection. It carries a reason attribute that explains the failure.
Because HTTPError is a subclass of URLError, always catch HTTPError first so that each error type is handled separately:
from urllib.request import urlopen from urllib.error import HTTPError, URLError try: response = urlopen("https://www.guru99.com/no-such-page.html") data = response.read() except HTTPError as error: print("HTTP error:", error.code) except URLError as error: print("URL error:", error.reason)
Handling these exceptions keeps your program from crashing and lets you log the problem, retry the request, or fall back to cached data.
Как да изтеглите файл от URL Using urllib
Четене на a URL Записването в паметта работи за малки страници, но за изображения, PDF документи или набори от данни е по-лесно отговорът да се запише директно на диск. Модулът urllib.request предлага два прости начина за това.
The urlretrieve() function downloads a URL директно към локален файл в един ред:
from urllib.request import urlretrieve urlretrieve("https://www.python.org/static/img/python-logo.png", "logo.png")
For more control, open the URL and write the bytes yourself. Open the local file in binary mode because urlopen() returns bytes, not text:
from urllib.request import urlopen with urlopen("https://example.com/data.zip") as response: with open("data.zip", "wb") as file: file.write(response.read())
For very large files, read and write in a loop using response.read(8192) so the whole file is never held in memory at once.
urllib срещу библиотеката за заявки в Python
urllib е част от Python стандартна библиотека, така че работи навсякъде без инсталация. Библиотеката за заявки от трети страни не е вградена, но много разработчици я предпочитат за ежедневна HTTP работа, защото синтаксисът ѝ е по-кратък и по-четлив.
Основните разлики са:
- Монтаж: urllib ships with Python, while requests must be installed with pip.
- Декодирането: urllib връща сурови байтове, които декодирате сами, докато requests декодира текст и JSON автоматично.
- Удобство: Заявките обработват сесии, бисквитки и персонализирани заглавки с по-малко код.
- Зависимости: urllib adds none, while requests relies on urllib3 underneath.
Choose urllib when you want zero dependencies or only need a quick, one-off request. Choose requests for larger projects that involve authentication, sessions, or frequent API calls. Both send the same underlying HTTP requests, so the decision comes down to convenience versus a smaller dependency list.


