zoukankan      html  css  js  c++  java
  • 用python零基础写爬虫--编写第一个网络爬虫 -2 设置用户代理

    1.设置用户代理

    默认情况下,urliib2使用python-urllib、2.7 作为用户代理下载网页内容,其中2.7是python的版本号。为避免一些网站禁封这个默认的用户代理,确保下载更加可靠,我们需要控制用户代理的设定。下面代码对download函数设定了一个名称为 “wswp” 的用户代理。

    import urllib2
    def download(url,user_agent='wswp', num_retries=2):
    print 'downloading:',url
    headers={'User-agent':user_agent}
    request=urllib2.Request(url,headers=headers)
    try:
    html=urllib2.urlopen(url).read()
    except urllib2.URLError as e:
    print 'download error:', e.reason
    html=None
    if num_retries>0:
    if hasattr(e, 'code') and 500<=e.code<600:
    #recursively retry 5XX http errors
    return download(url, user_agent,num_retries-1)
    return html


  • 相关阅读:
    手机适配与viewport
    Vue组件之间的传值
    作用域链、闭包以及this的使用
    浏览器兼容性
    闭包
    BFC自适应布局
    Mybatis 事务管理
    Mybatis数据源
    Mybatis 缓存分析
    设计模式之禅(2)-设计模式
  • 原文地址:https://www.cnblogs.com/mrruning/p/7637441.html
Copyright © 2011-2022 走看看