目标网站 http://help.tongtool.com/service.html?groupId=2
抓取的数据分析:先从html源代码分析,发现帮助文档的内容,都不存在于源代码中,所以不能直接用request.get("http://help.tongtool.com/service.html?groupId=2")来获取了。F12查看接口请求信息,一共包含两个请求url
http://help.tongtool.com/category/buildCategoryTreeHavingChildren 和http://help.tongtool.com/docs/listDocsPage?categoryId=306&pageSize=20&pageNum=1,查看两个请求的返回结果,第一个返回了了整个帮助文档的目录结构,部分返回数据如下:
第二个请求返回就是我们需要抓取的帮助信息详情了
从返回的结果里面,可以看到有我们需要抓取的信息有标题、内容、图片。再分析第二个请求url的结构,有一个关键词categoryId=306 感觉帮助文档的每个帮助信息,应该就是通过这个iD信息来存储的。于是尝试点击另一条帮助信息,查看请求的url,两者进行比较,果然是只有这个categoryId的值发生的改变。
以上综述,就是只要获取到所有帮助信息对应的categoryId,然后通过http://help.tongtool.com/docs/listDocsPage?categoryId=306&pageSize=20&pageNum=1这个链接,来改变categoryid的值,就可以循环获取到所有的帮助内容了。那么接下来就是如何获取所有的categoryid了。
获取categoryid
此时再回头看第一个链接的返回结果,不难看出返回的json中,有很多的id,并且每个id都不一样,这个时候就可以试想这里的id是不是就是我们需要的categoryid呢?我们可以做如下验证,我们以下面这个为例子
可以看到id235对应的帮助信息是其他导入方式,那么我们将235替换后访问试试,返回的结果如下:
这么一看,两者的信息就对应上了,接下来就是如何去获取所有id了。通过对json格式的分析,我们很容易就能掌握规律,这里就不做叙述了。大致获取的方法如下:
def categoryId():
"获取文档对应的id"
document_page=requests.get("http://help.tongtool.com/category/buildCategoryTreeHavingChildren")
ducument_result = document_page.json()
erp_help=ducument_result.get('datas')[0].get('childrenList')[0] #get('childrenList')[0]为ERP [1]为listing []
"得到帮助文档内容"
help_infos=erp_help.get('childrenList')[0].get('childrenList')
categoryIds=[]
for i in help_infos:
"获取一级菜单下面的子信息"
sub_info=i.get('childrenList') #list
for j in sub_info:
categoryIds.append(j.get('id'))
return categoryIds
这样就获取到了所有的categorys了
循环获取每条帮助内容
已知所有的categoryid后,剩下的就是依次通过每个id,来获取具体的帮助信息了。可以先拿一个id作为例子,实现玩一个后,再最外层套上循环就可以了。
page=requests.get("http://help.tongtool.com/docs/listDocsPage?categoryId=189&pageSize=20&pageNum=1")
result=page.json()
contents=result.get('datas').get('list')
for content in contents:
"存在多个的时候逐个读取"
all_contents = "" #帮助文档内容
title = content.get('title') #标题
if ":" in title:
title=title.split(":")[0] #存在一个报错的地方,先这么处理
if not os.path.exists('d://tmp//{0}'.format(title)):
os.makedirs('d://tmp//{0}'.format(title))
file_text = '{0}.txt'.format(title) #每条帮助信息一个文档,用标题做文件名
content_text = content.get('content')
html = etree.HTML(content_text) #使用etree来处理结果
"解析文本内容"
html_contents = html.xpath("//*/text()") #通过xpath来获取帮助内容
for html_content in html_contents:
all_contents = all_contents + html_content + '\n'
"解析帮助图片"
html_pages=html.xpath("//img/@src")
"创建文件夹来存储图片"
for page in html_pages:
filename = page.split('/')[-1]
print ('准备下载:'+page)
“url过滤和格式化”
if 'help' not in page:
print ('过滤链接:'+page)
continue
if "http" not in page:
page="http:"+page
ur.urlretrieve( page, os.path.join("d://tmp",title,filename))
file = open('d:\\tmp\\{1}\\{0}'.format(file_text,title), 'w', encoding='utf-8')
file.write(all_contents)
这里说明下,一个ID所对应的帮助信息可能是多条的,如下图,存在多条的时候就要循环逐个读取了。
这样执行后,就会生成多个文件夹,每个文件夹是一个帮助信息,里面存储了帮助信息的所有内容,包含图片和文本。
这样就实现了一个id的所有帮助信息抓取,接下来就是循环来读取categoryid,来获取所有的帮助信息了。
以上只是一个简单的实现,接下来需要优化的地方包含1、多线程的处理 2、读取数据存储到数据库