zoukankan      html  css  js  c++  java
  • python爬虫使用Xpath爬取指定位置的内容

    今天学习python的爬虫方法,发现用python来进行爬虫是真的舒服省事。该方法主要使用的是创建树形结构,利用xpath来定位。然后进行爬取

    代码及结果如下:

    #coding:utf-8
    import importlib,sys
    importlib.reload(sys)
    from lxml import etree
    import  requests
    from chardet import detect

    url='http://www.imooc.com/search/article?words=大数据'
    resp=requests.get(url,timeout=15)

    ecoding=detect(resp.content).get('encoding')
    html=resp.content.decode(ecoding)

    tree=etree.HTML(html)
    nn=tree.xpath('//div[@id="main"]/div[1]/div[2]/div[1]/div[2]/div[1]/a[1]/span/text()')
    print (nn)
    mm=tree.xpath('//div[@id="main"]/div[1]/div[2]/div[1]/div[2]/div[1]/a[1]/text()')
    print (mm)

    with open('r1.txt','w') as f: #在当前路径下,以写的方式打开一个名为'url.txt',如果不存在则创建
       
    for item in nn:
            f.write(item)
    with open('r1.txt','a') as f:
        for item in mm:
            f.write(item)

    kk=tree.xpath('//div[@id="main"]/div[1]/div[2]/div[1]/div[2]/div[1]/a[1]/span/@class')
    print( kk)

    这个网页好像里面没东西了,之前的txt又丢了,所以就不放结果截图了

  • 相关阅读:
    一行代码搞定图片缩放、旋转、加水印
    如何学习 Webpack
    Webpack 概念
    Webpack 入门
    asp.net core教程 (一)
    asp.net core教程 (二)
    ap.net core 教程(三)
    Grafana 安装配置
    zabbix-3.0.x LTS源码安装配置
    MariaDB Security
  • 原文地址:https://www.cnblogs.com/mhj666/p/11052109.html
Copyright © 2011-2022 走看看