今天学习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[@]/div[1]/div[2]/div[1]/div[2]/div[1]/a[1]/span/text()')
print (nn)
mm=tree.xpath('//div[@]/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[@]/div[1]/div[2]/div[1]/div[2]/div[1]/a[1]/span/@class')
print( kk)

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

相关文章:

  • 2021-09-20
  • 2021-09-20
  • 2021-09-20
  • 2021-12-22
  • 2022-12-23
  • 2021-09-20
  • 2021-11-04
  • 2021-12-30
猜你喜欢
  • 2021-12-27
  • 2021-11-27
  • 2021-04-03
  • 2021-09-20
  • 2021-09-20
  • 2021-11-10
相关资源
相似解决方案