当前位置:   article > 正文

python爬虫自学网站_Python爬虫学习——获取网页

python爬虫自学网站

通过GET请求获取返回的网页,其中加入了User-agent信息,不然会抛出"HTTP Error 403: Forbidden"异常,

因为有些网站为了防止这种没有User-agent信息的访问,会验证请求信息中的UserAgent(它的信息包括硬件平台、系统软件、应用软件和用户个人偏好),如果UserAgent存在异常或者是不存在,那么这次请求将会被拒绝。

#coding=utf-8

import urllib2

import re

#使用Python2.7

def getHtml(url,user_agent="wswp",num_retries=2):#下载网页,如果下载失败重新下载两次

print '开始下载网页:',url

headers = {"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 "下载失败:",e.reason

html = None

if num_retries > 0:

if hasattr(e,'code') and 500 <= e.code < 600:

return getHtml(url,num_retries-1)

return html

if __name__ == '__main__':

html = getHtml("http://www.baidu.com")

print html

print "结束"

0134f9808668402448db4f33e9ebb9a4.png

73c5a002ee6572e2ce13dfe6ca80b89f.png

...

bf1b5a4c4a315f5201f56d05ca0e73a7.png

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/1006844
推荐阅读
相关标签
  

闽ICP备14008679号