网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Python教程:常用网页字符串处理技巧

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

成都创新互联是一家专业提供灵石企业网站建设,专注与网站制作、成都做网站H5技术、小程序制作等业务。10年已为灵石众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。

1.去掉重复空格

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

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

s = "hello\nhello\nhello hello\n"
print(s)
s = s.replace("\n","")
print(s)

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

s = "hello\nhello\nhello hello\n"
print(s.find('\n'))
print(s.find('la'))

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

s = "hello\nhello\nhello hello\n"
print(s.rfind('\n'))
print(s.rfind('la'))

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

s = "hello\nhello\nhello hello\n"
print(list(s))

6.查找所有匹配的子串

import re

s = "hello\nhello\nhello hello\n"
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('\n','') # 如果想去掉回车可以加上这行
print(content)

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

from bs4 import BeautifulSoup

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

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

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''

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

或者提取出所有标签和标签

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

这些属于beautifulsoup的内容了

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

import re
re.split('; |, ',str)

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

网页标题:Python教程:常用网页字符串处理技巧
网站URL:http://bjjierui.cn/article/dsogjcj.html

其他资讯