爬取网页中的链接

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wlxsq/article/details/84454886

获取网页内容

1、引入库
import urllib
import urllib.request
2、获取网页内的所有数据
data = urllib.request.urlopen(“http://www.baidu.com").read()
3、将数据转换成UTF-8编码
data = data.decode(‘UTF-8’)
4、查看网页上获取的数据
print(data)

对网页内容进行筛选

1、引入库
import re
2、正则表达式设定匹配内容
linkre = re.compile('href=\"(.+?)\"')
3、遍历所有的匹配项

    for x in linkre.findall(data):
    	if 'http' in x
    		print('新增网址--->  ' + x)

4、查看显示结果
这就是网址页面代码里的所有href链接

将爬取的内容保存至文本文件

1、打开文件对象

file = open('文件路径','w')

2、将文件内容逐行写入文件

for x in linkre.findall(data):
	if 'http' in x:
		file.write(x + '\n)

猜你喜欢

转载自blog.csdn.net/wlxsq/article/details/84454886
今日推荐