Python Urllib.Request और urlopen() का उपयोग करके इंटरनेट एक्सेस

यूआरएललिब क्या है?

urllib एक है Python module that can be used for opening URLs. It defines functions and classes to help in URL कार्रवाई।

- Python आप इंटरनेट से XML, HTML, JSON आदि जैसे डेटा तक पहुंच और पुनर्प्राप्त भी कर सकते हैं। आप इसका उपयोग भी कर सकते हैं Python to work with this data directly. In this tutorial we are going to see how we can retrieve data from the web. For example, here we used a guru99 video URL, and we are going to access this video URL का उपयोग Python as well as print HTML file of this URL.

कैसे खोलें URL using Urllib

Before we run the code to connect to Internet data, we need to import statement for URL library module or “urllib”.

प्रारंभिक URL using Urllib

  • urllib आयात करें
  • अपना मुख्य कार्य परिभाषित करें
  • वेरिएबल webUrl घोषित करें
  • Then call the urlopen function on the URL lib library
  • RSI URL we are opening is guru99 tutorial on youtube
  • अब हम परिणाम कोड प्रिंट करेंगे
  • परिणाम कोड को हमारे द्वारा बनाए गए webUrl वेरिएबल पर getcode फ़ंक्शन को कॉल करके प्राप्त किया जाता है
  • हम इसे एक स्ट्रिंग में परिवर्तित करने जा रहे हैं, ताकि इसे हमारे स्ट्रिंग "परिणाम कोड" के साथ संयोजित किया जा सके
  • यह एक नियमित HTTP कोड “200” होगा, जो दर्शाता है कि http अनुरोध सफलतापूर्वक संसाधित हो गया है

How to get HTML file form URL in Python

आप HTML फ़ाइल को “read function” का उपयोग करके भी पढ़ सकते हैं Python, और जब आप कोड चलाएंगे, तो HTML फ़ाइल कंसोल में दिखाई देगी।

HTML file form URL in Python

  • Call the read function on the webURL परिवर्तनशील
  • रीड वेरिएबल डेटा फ़ाइलों की सामग्री को पढ़ने की अनुमति देता है
  • Read the entire content of the URL into a variable called data
  • कोड चलाएँ- यह डेटा को HTML प्रारूप में प्रिंट करेगा

यहाँ पूरा कोड है

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)

इस पोस्ट को संक्षेप में इस प्रकार लिखें: