正则取html的文本值
时间: 2023-10-08 11:05:16 浏览: 41
如果要使用正则表达式取出HTML标签中的文本值,可以使用Python的`re`模块。
例如,如果想要取出`<div>`标签中的文本,可以使用以下代码:
```python
import re
html_string = '<div>hello world</div>'
text = re.search('<div>(.*?)</div>', html_string).group(1)
print(text)
```
其中,`'<div>hello world</div>'`是HTML字符串,`'<div>(.*?)</div>'`是匹配`<div>`标签中的内容的正则表达式,其中`(.*?)`表示非贪婪匹配任意字符。`re.search()`函数会返回第一个匹配的结果,使用`.group(1)`获取第一个括号中匹配到的内容,即`'hello world'`。
如果要取出所有`<div>`标签中的文本,可以使用`re.findall()`函数,例如:
```python
import re
html_string = '<div>hello world</div><div>goodbye world</div>'
texts = re.findall('<div>(.*?)</div>', html_string)
print(texts)
```
其中,`'<div>hello world</div><div>goodbye world</div>'`是HTML字符串,`'<div>(.*?)</div>'`是匹配`<div>`标签中的内容的正则表达式,使用`re.findall()`函数可以返回所有匹配的结果,即`['hello world', 'goodbye world']`。