响应有两种:JSON数据和HTML页面,对于后者就需要进行解析HTML Documen得到我们需要的信息。
① xpath使用
可以提前安装xpath插件,也可以自己从HTML源码解析。
            
            
              python
              
              
            
          
          (1)打开chrome浏览器
(2)点击右上角小圆点
(3)更多工具
(4)扩展程序
(5)拖拽xpath插件到扩展程序中
(6)如果crx文件失效,需要将后缀修改zip
(7)再次拖拽
(8)关闭浏览器重新打开
(9)ctrl + shift + x
(10)出现小黑框1.安装lxml库
            
            
              python
              
              
            
          
          pip install lxml ‐i https://pypi.douban.com/simple2.导入lxml.etree
            
            
              python
              
              
            
          
          from lxml import etree3.etree.parse() 解析本地文件得到HTML Document
            
            
              python
              
              
            
          
          html_tree = etree.parse('XX.html')4.etree.HTML() 服务器响应文件得到HTML Document
            
            
              python
              
              
            
          
          html_tree = etree.HTML(response.read().decode('utf‐8')5.html_tree.xpath(xpath路径)解析目标信息
② 基本语法
xpath基本语法:
            
            
              python
              
              
            
          
          1.路径查询
//:查找所有子孙节点,不考虑层级关系
/ :找直接子节点
2.谓词查询
//div[@id]
//div[@id="maincontent"]
3.属性查询
//@class
4.模糊查询
//div[contains(@id, "he")]
//div[starts‐with(@id, "he")]
5.内容查询
//div/h1/text()
6.逻辑运算
//div[@id="head" and @class="s_down"]
//title | //price③ xpath使用案例
查找ul下面的li
            
            
              python
              
              
            
          
          # li_list = tree.xpath('//body/ul/li')查找所有有id的属性的li标签
            
            
              python
              
              
            
          
          # text()获取标签中的内容
# li_list = tree.xpath('//ul/li[@id]/text()')找到id为l1的li标签 注意引号的问题
            
            
              python
              
              
            
          
          # li_list = tree.xpath('//ul/li[@id="l1"]/text()')查找到id为l1的li标签的class的属性值
            
            
              python
              
              
            
          
          # li = tree.xpath('//ul/li[@id="l1"]/@class')查询id中包含l的li标签
            
            
              python
              
              
            
          
          # li_list = tree.xpath('//ul/li[contains(@id,"l")]/text()')查询id的值以l开头的li标签
            
            
              python
              
              
            
          
          # li_list = tree.xpath('//ul/li[starts-with(@id,"c")]/text()')查询id为l1和class为c1的
            
            
              python
              
              
            
          
          # li_list = tree.xpath('//ul/li[@id="l1" and @class="c1"]/text()')
li_list = tree.xpath('//ul/li[@id="l1"]/text() | //ul/li[@id="l2"]/text()')
# 判断列表的长度
print(li_list)
print(len(li_list))获取class="week"的第一个dd的文本节点
            
            
              java
              
              
            
          
          response = requests.get(url=url,headers=headers)
# print(response.text)
# print(response.content)
tree = html.fromstring(response.text)
# 这里得到的是一个数组
first_week_text_list = tree.xpath('//dl[@class="weather_info"]//dd[@class="week"][1]/text()')
if first_week_text_list:  # 检查是否找到了任何文本
    # 将所有文本节点合并成一个字符串并去除空白字符
    first_week_text = ''.join(first_week_text_list).strip()
    print(f"First week text: {first_week_text}")
else:
    print("No text found in the <dd> elements with class 'week'.")④ 爬取站长素材情侣图片案例
            
            
              python
              
              
            
          
          # (1) 请求对象的定制
# (2)获取网页的源码
# (3)下载
# 需求 下载的前十页的图片
# https://sc.chinaz.com/tupian/qinglvtupian.html   1
# https://sc.chinaz.com/tupian/qinglvtupian_page.html
import urllib.request
from lxml import etree
def create_request(page):
    if(page == 1):
        url = 'https://sc.chinaz.com/tupian/qinglvtupian.html'
    else:
        url = 'https://sc.chinaz.com/tupian/qinglvtupian_' + str(page) + '.html'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
    }
    request = urllib.request.Request(url = url, headers = headers)
    return request
def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content
def down_load(content):
#     下载图片
    # urllib.request.urlretrieve('图片地址','文件的名字')
    tree = etree.HTML(content)
    name_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@alt')
    # 一般设计图片的网站都会进行懒加载
    src_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]//img/@data-original')
    for i in range(len(name_list)):
        name = name_list[i]
        src = src_list[i]
        url = 'https:' + src
        urllib.request.urlretrieve(url=url,filename='./loveImg/' + name + '.jpg')
if __name__ == '__main__':
    start_page = int(input('请输入起始页码'))
    end_page = int(input('请输入结束页码'))
    for page in range(start_page,end_page+1):
        # (1) 请求对象的定制
        request = create_request(page)
        # (2)获取网页的源码
        content = get_content(request)
        # (3)下载
        down_load(content)