• Python常用网页字符串处理技巧


    首先一些Python字符串处理的简易常用的用法。其他的以后用到再补充。

    1.去掉重复空格

    s = "hello   hello   hello"
    s = ' '.join(s.split())

    2.去掉所有回车(或其他字符或字符串)

    s = "hello
    hello
    hello hello
    "
    print(s)
    s = s.replace("
    ","")
    print(s)

    3.查找字符串首次出现的位置(没有返回-1)

    s = "hello
    hello
    hello hello
    "
    print(s.find('
    '))
    print(s.find('la'))

    4.查找字符串从后往前找首次出现的位置(没有返回-1)

    s = "hello
    hello
    hello hello
    "
    print(s.rfind('
    '))
    print(s.rfind('la'))

    5.将字符串转化成列表list

    s = "hello
    hello
    hello hello
    "
    print(list(s))

    6.查找所有匹配的子串

    import re
    
    s = "hello
    hello
    hello hello
    "
    print(re.findall('hello',s)) # hello也可以换成正则表达式

    然后是网页字符串处理的高端用法:(综合运用requests模块,beautifulsoup模块,re模块等)

    1.requests获取一个链接的内容并原封不动写入文件

    import requests
    
    r = requests.get('https://baike.baidu.com')
    with open('test.html', 'wb') as fd:
        for chunk in r.iter_content(100):
            fd.write(chunk)

    2.读取一个文件的所有内容存到一个字符串里

    # encoding : utf-8
    
    with open('test.html','r',encoding='utf-8') as f:
        content = f.readlines()
    content = ''.join(content)
    # content = content.replace('
    ','') # 如果想去掉回车可以加上这行
    print(content)

    3.把网页字符串用BeautifulSoup存起来处理

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(content,'html.parser')
    print(soup.prettify())

    4.存到BeautifulSoup里之后这个字符串就可以任你摆布了,比如:提取出所有<a>标签

    soup = BeautifulSoup(content,'html.parser')
    print(soup.find_all('a'))

    或者提取出所有<a>标签和<b>标签

    soup = BeautifulSoup(content,'html.parser')
    print(soup.find_all(['a','b']))

    这些属于beautifulsoup的内容了,可以看官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

    也可以看我的另一篇博客:http://www.cnblogs.com/itlqs/p/5902678.html

    5.多个关键字切分字符串

    import re
    re.split('; |, ',str)
    
    >>> a='Beautiful, is; better*than
    ugly'
    >>> import re
    >>> re.split('; |, |*|
    ',a)
    ['Beautiful', 'is', 'better', 'than', 'ugly']
  • 相关阅读:
    Mysql添加用户和数据库
    Ubuntu Apache vhost不执行php小记
    buff/cache内存占用过多
    yii2 返回json和文件下载
    yii2 activeform 替換 form-gruop
    VSCode+Ionic+Apache Ripple开发环境搭建
    安装ionic出现node-sass无法下载的解决方法
    VS2015 + Cordova Html5开发使用Crosswalk Web引擎
    visual studio 2015 + Cordova 开发环境搭建
    ADSL自动更换IP地址源代码
  • 原文地址:https://www.cnblogs.com/itlqs/p/5942374.html
Copyright © 2020-2023  润新知