Python crawler Learning--Get web page

Source: Internet
Author: User

Get The returned page with the user-agent information , otherwise it will throw an "HTTP Error 403:forbidden" Exception .

Because some websites to prevent this kind of access without user-agent information, will verify the request information in the UserAgent(its information including hardware platform, system software, application software and user's personal preferences), If useragent exists or does not exist, then this request will be rejected.

#coding =utf-8import urllib2import re# use python2.7def gethtml (url,user_agent= "Wswp", num_retries=2): #下载网页, If download fails re-download two times print ' Start download page: ', urlheaders = {' user-agent ': user_agent} #headers = {#   ' user-agent ': ' mozilla/5.0 ( Windows NT 6.1; rv:24.0) gecko/20100101 firefox/24.0 ', #   ' cookie ': Cookie#}request = urllib2. Request (Url,headers=headers) Try:    HTML = urllib2.urlopen (Request). Read () #GET请求except urllib2. Urlerror as E:print "Download failed:", e.reasonhtml = Noneif num_retries > 0:if hasattr (E, ' Code ') and <= E.code < 600:re Turn gethtml (url,num_retries-1) return htmlif __name__ = ' __main__ ': html = gethtml ("http://www.baidu.com") print Htmlprint "End"

...

Python crawler Learning--Get web page

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.