python-基于xpath的聚焦爬虫学习

  XPath 是一门在 XML 文档中查找信息的语言。

  XPath 是 XSLT 中的主要元素。

  XQuery 和 XPointer 均构建于 XPath 表达式之上。

  他可以适用于 多种语言,个人感觉比较实用。

  解析原理 类似于bs4:

    from lxml import etree
  实例化一个etree对象,将需要加载的数据加载到该对象中
  本地,etree.parse(filepath) 互联网etree.HTML('page_text')
  通过调用etree调用xpath()中的方法定位标签得到属性或者数据 xpath('xpath表达式')
  下面可以看一下我的爬取五八同城房源只是名称信息:
  
#-*- codeing = utf-8 -*-
#@Time :  14:50
#@Auther : wyt
#@File : 58房源信息.py
#@Software : PyCharm
import requests
from lxml import etree
if __name__ == '__main__':
    url = 'https://sjz.58.com/ershoufang/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0'
    }
    page_text = requests.get(url=url,headers=headers).text
    # print(page_text)
    # html不符合lxml的编码规范,需要进行设置
    parser = etree.HTMLParser(encoding='utf-8')
    tree = etree.HTML(page_text,parser=parser)
    li = tree.xpath('//ul[@class="house-list-wrap"]/li')
    fp = open('D:StudyPythonscrapyhouseinfo.txt', 'w', encoding='utf-8')
    for i in li:
        name = i.xpath('./div[2]/h2/a/text()')[0]
        print(name)
    #     fp.write(name+'
')
    # fp.close()
    # print('房源信息爬取成功')

  这个案例是爬取图片(宅男福利):

#-*- codeing = utf-8 -*-
#@Time :  15:57
#@Auther : wyt
#@File : xpath爬取图片.py
#@Software : PyCharm
import requests
from lxml import etree
if __name__ == '__main__':
    url = 'http://pic.netbian.com/4kmeinv/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0'
    }
    resp = requests.get(url=url,headers=headers)
    # resp.encoding = 'utf-8'
    page_text = resp.text
    # print(page_text)
    parser = etree.HTMLParser(encoding='utf-8')
    tree = etree.HTML(page_text, parser=parser)
    li = tree.xpath('//ul[@class="clearfix"]/li')
    for i in  li:
        image_src = 'http://pic.netbian.com'+i.xpath('./a/img/@src')[0]
        image_alt = i.xpath('./a/img/@alt')[0]
        # 通用处理中文乱码的解决方案,然后重新赋值
        image_alt=image_alt.encode('iso-8859-1').decode('gbk')
        # print(image_alt+':'+image_src)
        # 图片数据是以二进制存储的   content
        image = requests.get(url=image_src,headers=headers).content
        filename = 'D:StudyPythonscrapyimg\'+image_alt+'.jpg'
        fp = open(filename,'wb')
        fp.write(image)
    print('4k图片爬取成功')

  爬取图片的时候遇到了中文乱码的问题:

    两种解决办法:1、直接对返回响应数据的对象进行编码设置。爬取图片的代码即可。

           2、直接对出现乱码的地方进行编码设置。

 
原文地址:https://www.cnblogs.com/moxihuishou/p/13956326.html