python网络爬虫(二)编写第一个爬虫

news/2024/7/19 11:08:23 标签: 爬虫, python, 数据库

为什么80%的码农都做不了架构师?>>>   hot3.png

抓取网站数据通常需要先下载网页,这个过程称为爬取。爬取网站通常有3种常见方法:

  • 爬取网站地图
  • 遍历每个页面的数据库ID
  • 跟踪每个网页链接

想要爬取网页,首先要将其下载下来。下面使用Python的urllib2模块下载URL。

import urllib2

def download(url):
    html = urllib2.urlopen(url).read()
    return html

download('http://www.baidu.com')

带有扑捉异常的代码:

import urllib2

def download(url):
    print 'downloadimng :' , url
    try:
        html = urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print 'Download error:', e.reason
        html = None
    return html

download('http://www.baidu.com')

1.重试下载

下载时遇到错误是常有的,优势服务器返回503 Service Unavailable错误时,对于此类错误,我们可以重试下载。如果返回404,则说明网页目前不存在,不需要重新下载。4xx是请求存在问题,5xx是服务器端存在问题,所以确保download函数在5xx错误是重试下载。 下面代码是支持重试下载的代码:

import urllib2


def download(url, num_retries = 2):
    print 'downloadimng :' , url
    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:
                return download(url, num_retries-1)
    return html

download('http://httpstat.us/500')

下面是返回的结果:

downloadimng : http://httpstat.us/500
Download error: Internal Server Error
downloadimng : http://httpstat.us/500
Download error: Internal Server Error
downloadimng : http://httpstat.us/500
Download error: Internal Server Error

download函数在收到500错误后,重试了2次才放弃。

2.设置用户代理

默认情况下,urllib2使用的是Python-urllib/2.7作为用户代理下载网内容。一些目标网站会封禁这个默认代理,这时就需要修改默认的用户代理。

import urllib2

def download(url, user_agent='wswp',  num_retries = 2):
    print 'downloadimng :' , 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:
                return download(url, num_retries-1)
    return html

download('http://www.meetup.com/')

网站地图爬虫

def crawl_sitemap(url):
    sitemap = download(url)
    links = re.findall('<loc>(.*?)</loc>', sitemap)
    for link in links:
        html = download(link

ID遍历爬虫

for page in itertools.count(1):
    url = 'http://blog.jobbole.com/%d' % page
    html = download(url)
    if html is None:
        break
    else:
        pass

链接爬虫: 通过跟踪链接的形式,我们的爬虫看起来更像普通用户。我们可以很轻易的下载整个网站的页面,通常我们感兴趣的是网站一部分网页中的一部分信息,我们可以使用正则表达式确定下载那些页面中的特定信息。

转载于:https://my.oschina.net/clgo/blog/841406


http://www.niftyadmin.cn/n/707750.html

相关文章

Winows下程序崩溃自动创建Dump文件以方便跟踪问题

需要头文件&#xff1a;#include <DbgHelp.h>和库DbgHelp.lib 首先定义一个默认的异常处理回调函数&#xff1a; LONG CrashHandler(struct _EXCEPTION_POINTERS* pExceptionInfo) {std::string dumpFileName "./CrashDump.dump";HANDLE hDumpFile CreateF…

SQL批量更新数据

SQL批量更新数据step1:导入Excel数据&#xff0c; 具体见百度。注意点&#xff1a;一列中含有float型数据和文本数据的时候&#xff0c;导入要将Excel中的表格属性改成文本&#xff0c;或在数字项目前加个单引号。 step2:更新相同数据,联表查询更新数据update tbparts set pdlp…

一个DrectX程序的基本流程(DXD10以下)

本文章通过一个简单的示例来说明一下一个D3D程序的基本流程 [注]&#xff1a;本程序使用DirectX 9.0实现并使用了Qt&#xff0c;参照的时候不要链接库链接错了哦. 示例<使用D3D渲染一个jpg图像到窗口> 步骤&#xff1a; 1、创建一个Windows窗口程序 2、初始化D3D 3、渲…

postman 测试excel下载_postman 测试Excel文件导入导出功能

ORACLE中的LTRIM、RTRIM和TRIMLTRIM.RTRIM和TRIM在ORACLE中的用法:1.LTRIM(C1,C2)其中C1和C2都可以字符串,例如C1是Miss Liu,C2MisL等等.这是第一个和SQL SERVER不 ...PAT 1019&period; 数字黑洞 &lpar;20&rpar;给定任一个各位数字不完全相同的4位正整数,如果我们先…

模拟UI中国首页

2019独角兽企业重金招聘Python工程师标准>>> <!DOCTYPE html> <html> <head><meta http-equiv"Content-Type" content"text/html;charsetutf-8"><title>UI中国</title><meta name"Keywords" …

jQuery格式化json的输出格式

2019独角兽企业重金招聘Python工程师标准>>> 方法&#xff1a;JSON.stringify(jsonObj, null, \t); 输出格式&#xff0c;以下格式在textArea或页面中也是这样展示&#xff1a; "{ "region": null, "mcaPath": null, "pkgName&qu…

用c++实现分割字符串函数(分割std::string)

2018.09.21更新于文章尾部&#xff1a;第二个函数优化了处理时间&#xff0c;占用更少内存和时间 2020.05.07更新于前两个函数&#xff1a;加入了说明注释&#xff0c;方便理解 2022.06.06更新一个比较巧妙的方法<GetStringSplit> ----------------------------------…

setContentType与setCharacterEncoding的区别

setCharacterEncoding只是设置字符的编码方式 setContentType除了可以设置字符的编码方式还能设置文档内容的类型 1.setCharacterEncoding response.setCharacterEncoding("UTF-8"); PrintWriter out response.getWriter(); out.println("<!DOCTYPE html&g…