• xpath基本使用


    xpath基本使用

    一.安装lxml包

    pip install lxml

    二.使用

    1.使用:

    from lxml import etree   # 导包
    import requests

    response = resquests.get('www.baidu.com')
    # 生成一个html对象
    # html = etree.parse(html文档)   # 参数为 html文档
    html = etree.HTML(response.text)  # 参数为字符串文本
    div = html.xpath('xpath表达式')   # 返回一个文本列表

     

    1.获取最外面标签,遍历内部所有的子标签,获取标签文本

    content_list =div.xpath('.//div[@class="d_post_content j_d_post_content "]/text()').extract()

    2.正则去掉所有标签 <.*?> re.compile.sub()

    content_list=div.xpath('.//div[@class="d_post_content j_d_post_content "]')

    pattern=re.compile(r('<.*?>'),re.S)

    content=pattern.sub('',content_list)

    3./text() 获取标签的文本 //text()获取标签以及子标签的文本

    content_list = div.xpath(‘.//div[@class=”d_post_content j_d_post_content “]//text()’).extract()

    4 使用xpath(‘string(.)’)这种方式获取所有文本 并且拼接

    content_list=div.xpath('.//div[@class="d_post_content j_d_post_content "]').xpath('string(.)').extract()[0]+' '

    文本内容获取之后print(content_list)查看内容,如需处理格式,则如下:

    remove = re.compile('s') content = '' for string in content_list: string = remove.sub('',string) content += string

     

    string方法: content = div.xpath('string(.//div[@class="content"])').strip() # 获取该div下所有文本组成一个字符串

  • 相关阅读:
    关于HTTP以及TCP
    .NetCore表单提交文件
    C# Out变量
    .NET Core 网络数据采集 -- 使用AngleSharp做html解析
    C# 根据Url下载文件/获取文件流
    C# 模拟表单提交
    C# 获取Url路径的参数信息
    C# 采集页面数据
    .net core 3.1 设置可跨域
    C# json字符串转化成Dictionary
  • 原文地址:https://www.cnblogs.com/Deaseyy/p/11266786.html
Copyright © 2020-2023  润新知