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又丟了,所以就不放結果截圖了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM