zoukankan      html  css  js  c++  java
  • Python爬虫

    Python爬虫:调度器、网页下载器、解析器

    urllib2模块:用来下载网页

    方法1:最简洁的方法:

    import  urllib2

    #用urllib2的urlopen方法可以下载所需要下载的url,返回给response

    response = urllib2.urlopen('http://www.baidu.com')

     #获取状态码,如果是200表示获取成功

    print response.getcode()

    #读取内容

    cont = respone.read()

    例如:爬出艺库首页内容

    #!/usr/bin/env python
    #coding=utf8
    import urllib2
    response = urllib2.urlopen('http://www.eku.com.cn')
    print response.getcode()
    cont = response.read()
    print cont

    下载网页方法2:添加data,http header

    data:添加用户所需要的信息

    http header :添加http的头信息

    第二种方法

    import  urllib2

    #创建Request对象

    request = urllib2.Request(url)

    #添加数据

    request.add_data('a','1')

    #添加http的header

    request.add_header('User-agent','Mozilla/5.0')

    #发送请求获取结果

    response = urllib2.urlopen(request)

    第三种方法

     

     网页解析器:

    网页解析器:从网页中提取有价值数据的工具。

    Python有哪几种网页解析器:

    1、正则表达式

    2、html.parser

    3、beautiful soup  (属于Python第三方库,用于从HTML或xml中提取数据)

    4、lxml

    (1)创建Beautiful Soup 对象

    from bs4 import BeautifulSoup

    #根据HTML网页字符串创建BeautifulSoup 对象

    soup = BeautifulSoup(

              html_doc,      #HTML文档字符串

              'html.parser'     #HTML解析器

              from_encoding='utf8' #html文档的编码 

              )

     (2)搜索节点(find_all,find)

    #方法:find_all(name,attrs,string)

    访问节点信息:

    #得到节点:<a href='1.html'>Pyton</a>

    #获取查找到的节点的标签名称

    node.name

    #获取查找到的a节点的href属性

    node['href']

    #获取查找到的a节点的链接文字

    node.get_text()

  • 相关阅读:
    [文档].Altera 可选择的Nios II的Boot方法
    [原创].关于使用QII 10.0编译器无法编辑和查看中文的问题一个变通解决方案
    判断某程序是64位还是32位
    在调用RestoreSPSite时指定ContentDatabase
    CAML join
    ADODB.Connection Invalid connection error
    Sharepoint 如何修改Web.Config文件
    ActivateOnDefault & AutoActivateInCentralAdmin feature 属性
    Sharepoint 2010 解决DFWP Unable to display this Web Part 的问题
    Powershell点滴
  • 原文地址:https://www.cnblogs.com/sd880413/p/8027610.html
Copyright © 2011-2022 走看看