Python uses urllib2 to obtain the http Request status code. For example, pythonurllib2

Source: Internet
Author: User

Python uses urllib2 to obtain the http Request status code. For example, pythonurllib2

The verification code returned by the webpage is often needed for further processing.

The following code is a script written in python to obtain the http status code of a webpage.

#! /Usr/bin/python #-*-coding: UTF-8-*-# encoding = UTF-8 # Filename: states_code.py import urllib2 url = 'HTTP: // www.bkjia.com/'response = Nonetry: response = urllib2.urlopen (url, timeout = 5) response t urllib2.URLError as e: if hasattr (e, 'code'): print 'error code: ', e. code elif hasattr (e, 'reason '): print 'reason:', e. reasonfinally: if response: response. close ()


Http problems in python urllib2

Print 2 is returned only when the try code has no exception. If you say print 2 is never executed, there is a problem in the try code block.
 
In python, how does one obtain the webpage source code with a non-200 return code?

Non-200 may not have source code. You can refer to RFC2616, for example, 302 and 301. Then you can request the Location url in the header, and you can give up 5xx ......
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.