• 爬虫中xpath的特殊用法


    Xpath之starts-with(@属性名称,属性字符串相同部分) 以相同的字符开头的用法

    在做爬虫时解析html的源码时候可能会遇见以下这种标签,

    <div id="test-1"> 需要的内容1</div>
    <div id="test-2"> 需要的内容2</div>
    <div id="testfault"> 需要的内容3</div>

    我们发现这种标签都是id属性名称相差了一个数字或其他的字符串而已,在提取数据时完全没必要写三次xpath表达式.可以直接用以下这种方法去提取数据,

    1 selector = etree.HTML("带解析的HTML字符串源码")
    2 content = selector.xpath('//div[starts-with(@id,"test")]/text()')

    Xpath之xpath().string(.)

    标签嵌套(如下情况)

     1 <!doctype html>
     2 <html lang="en">
     3 <head lang="en">
     4     <meta charset="UTF-8">
     5     <meta name="viewport"
     6           content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
     7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     8     <title>Document</title>
     9 </head>
    10 <body>
    11     <div id="test3">
    12         我在左边.
    13         <span id="tiger">
    14             我在右边.
    15             <ul>我在上边
    16                 <li>我在下边</li>
    17             </ul>
    18             我在中间
    19         </span>
    20         我在这儿
    21     </div>
    22 </body>
    23 </html>

    类似这种的标签结构可以使用以下这种方式去提取数据

    1 data = selector.xpath('//div[@id="test3"]')[0]
    2 info = data.xpath('string(.)')
    3 content_2 = info.replace('
    ',' ').replace('  ',' ')
    4 print(content_2)
  • 相关阅读:
    Java方法_数组
    Java语句
    C#死锁示例
    Sqlserver限制用户访问指定数据库
    Stream 和 byte[] 之间的转换
    ContentType
    IIS7多站点ssl配置及http自动跳转到https
    google map api key配置
    remote: Incorrect username or password ( access token ) fatal: Authentication failed for
    IIS 404设置
  • 原文地址:https://www.cnblogs.com/Successful-people/p/10642741.html
Copyright © 2020-2023  润新知