当前位置: 首页 > Web前端 > HTML

Python学习笔记---爬取百度图片

时间:2023-04-02 15:07:06 HTML

我的博客只是记录学习python的学习过程和成长,不对任何文章的技术负责(^_^)要求:爬取百度图片项目分析:动态加载百度中的图片,出处无法通过请求匹配获取网页代码。经过尝试,我发现有一种更简单的方法是使用selenium来模拟爬行。动态加载很难,但是有更好的方法。看,我找到了json数据,可以直接处理请求,不需要用selenium。计划是首先导入包importrequestsimportjson并设置headers和paramsheaders={"User-Agent":"Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/78.0.3904.108Safari/537.36"}param={'tn':'resultjson_com','logid':'11450117138517082972','ipn':'rj','ct':'201326592','is':'','fp':'result','fr':'','word':'Quickpaint','queryWord':'Quickpaint','cl':'2','lm':'-1','ie':'utf-8','oe':'utf-8','adpicid':'','st':'','z':'','ic':'','hd':'','latest':'','copyright':'','s':'','se':'','tab':'','width':'','height':'','face':'','istype':'','qc':'','nc':'','expermode':'','nojc':'','isAsync':'','pn':'90','rn':'30','gsm':'5a','1673751010721':'',}数据请求和解析函数defparse(url):response=requests.get(url=url,headers=headers,params=param).json()img_list=response['data']forimginimg_list:try:img_name=img['fromPageTitle']print(img_name)img_url=img['replaceUrl'][0]['ObjUrl']print(img_url)except:pass为了分析多个网页,我们需要创建一个url列表来查看这两张图片的对比。只有pn发生了变化。显然我们可以猜到它的全名是page_num,s所以我们只需要对它进行操作就可以得到不同的数据url_list=[]foriinrange(90,301,30):url='https://image.baidu.com/search/acjson?tn=resultjson_com'\'&logid=11450117138517082972&ipn=rj&ct=201326592&is=&fp=result'\'&fr=&word=%E9%80%9F%E6%B6%82&queryWord=%E9%80%9F%E6%B6%82'\'&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=©right='\'&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&expermode=&nojc=&isAsync='\'&pn={}&rn=30&gsm=5a&1673751010721='.format(i)url_list.append(url)最后,调用函数如果__name__=='__main__':forurlinurl_list:parse(url=url)