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又丢了,所以就不放结果截图了

原文地址:https://www.cnblogs.com/mhj666/p/11052109.html