休息几天了,,写一个关于自动爬补天厂商及地址的脚本吧.

版本:Python 3.5

代码:


from lxml import etree
import re,os,threading
import urllib.request

def messageinfo(page):
dom=etree.HTML(page)#用html解析,保存成dom树
title=dom.xpath('/html//td/a')#取出厂商的名称
url=dom.xpath('/html//td[2]')#取出厂商url
titlelist=[]#初始化厂商名称的一个列表
urllist=[]#初始化厂商url的一个列表
newlist=[]#初始化厂商列表的一个列表
for x in title:#将厂商名称逐条取出
   title_list.append(x.text)#插入到title_list这个列表中
for y in url:#将厂商url逐条取出
url_list.append(y.text) #插入到url_list这个列表中
for k in range(len(title_list)):
new_tuple=(title_list[k],url_list[k])#将title_list和url_list两个列表中对应位置的数据取出来(title,url)
new_list.append(new_tuple)#插入到new_list这个新的列表中
return(new_list,url_list)#将厂商列表和url列表返回

def save_path(path,fileName,message):
if not os.path.exists(path): #判断path(补天)这个文件夹是否存在
os.mkdir(path)#不存在就创建
newFileName=fileName+'.txt'#拼接文件名(厂商列表.txt)存储在newFileName中
newFile=os.path.join(path,newFileName)#拼接路径(补天/厂商列表.txt)存储在newFile中
with open(newFile,'a') as f:#打开newFile这个文件(补天/厂商列表.txt)存储在变量f中,用a是追加(每次写入不会清空)
for s in message:#将厂商列表的内容逐行取出,message(也就是message_list)是一个列表,列表的每一个元素是个元组(title,url)
f.write('%s %s\n'%(s[0],s[1]))#s0和s1的内容写入到文件中

def save_url(path,fileName,message):
if not os.path.exists(path):#判断path(补天)这个文件夹是否存在
os.mkdir(path)#不存在就创建
newFileName=fileName+'.txt'#拼接文件名(url列表.txt)存储在newFileName中
newFile=os.path.join(path,newFileName)#拼接路径(补天/url列表.txt)存储在newFile中
with open(newFile,'a') as f:
for s in message:#将厂商列表的内容逐行取出,message(也就是murl_list)是一个列表
f.write('%s\n'%s)#将列表的每一个元素写入到文件中

def Spider(url):
message=urllib.request.urlopen(url)#解析url,返回的结果是内存地址
html=message.read()#用read()读出内容,存到html这个变量中
List=message_info(html)#调用message_info函数,函数返回的结果(new_list,url_list)这个元组存到List变量中
message_list=List[0]#List[0]保存的是new_list(厂商列表)的内容
url_list=List[1]#List[1]保存的是url_list(url列表)的内容
message_path=u'补天'#要保存的文件夹名称
message_fileName=u'厂商列表'#要保存的文件名称
url_fileName=u'URL列表'#要保存的文件名称
save_path(message_path,message_fileName,message_list)#调用save_path函数,保存厂商列表
save_url(message_path,url_fileName,url_list)##调用save_url函数,保存url列表

if __name == '__main':
for p in range(1,25):
start_url='https://butian.360.cn/company/lists/page/'+ str(p)#循环补天厂商列表的页数
Spider(start_url)

效果演示:


最后修改:2021 年 03 月 09 日
如果觉得我的文章对你有用,请随意赞赏