re库提取网页文本的方法

这是一种提取网页中的显示的文本内容,去除标签的方法。

主要用到了re库。直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding: utf-8 -*-
from urllib import request
import re

def get_html(url):
wp = request.urlopen(url) #打开连接
content = wp.read() #获取页面内容
content = content.decode(encoding='utf-8')
print(content)
first = re.findall(r"<p.+?>(.+?)</p>", content)
print(first)


for x in first:
#r1 = re.compile('[\u4e00-\u9fa5]{2,4}') # 匹配文字
#wordList = re.findall(r1, x)

wordList= re.sub(r'<(.+?)>', "", x)
for t in wordList:
k = open('test.htm', 'a')
k.write(t)
print (t)

url="https://mp.weixin.qq.com/s/JHoOoOH-3795hb3Y9LV7Gg"
get_html(url)

展示一些结果:

作者

Mch Wang

发布于

2019-04-07

更新于

2021-09-12

许可协议

评论