import requests
import re
resp_pat1list=[]
resp_pat1list2=[]
#请求头
header = {‘User-Agent’:‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36’}
#需要爬取的网页
url = ‘http://www.114best.com/tel/’
#爬取网页信息
resp_url = requests.get(url,headers=header).content.decode().replace(’\n’,’’).replace(’\t’,’’).replace(’ ‘,’’).replace(’\r’,’’)#去除换行空格等字符方便后边查找
print(resp_url)
#清洗数据
pat1 =r’<ahref="/tel/[\s\S]?/">(.?)[\s\S]?|(.?)[\s\S]?’#数据位于两种不同的标签
pat2 =r’<ahref="/tel/[\s\S]?/">[\s\S]?(.?)|[\s\S]?(.?)’
pat1 = re.compile(pat1,re.I)
pat2 = re.compile(pat2,re.I)
resp_pat1 =pat1.findall(resp_url)
resp_pat2 =pat2.findall(resp_url)
#对空值进行去除
for i in range(0,len(resp_pat1)):
if resp_pat1[i][0]==’’:
resp_pat1list.append(resp_pat1[i][1])
else:
resp_pat1list.append(resp_pat1[i][0])
print(resp_pat1list)
for i in range(0,len(resp_pat2)):
if resp_pat2[i][0]==’’:
resp_pat1list2.append(resp_pat2[i][1])
else:
resp_pat1list2.append(resp_pat2[i][0])
print(resp_pat1list2)
#对数据进行整理并写入文件
for i in range(0,len(resp_pat1list)):
data=‘单位’+resp_pat1list[i]+‘电话是:’+resp_pat1list2[i]
with open(‘c:\list.txt’,‘a’)as f:
f.write(’\n’+data)# 写入换行操作
print(‘正在写入第’+str(i+1))