300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python爬虫实战 requests模块 Python实现抓取头条街拍美图

python爬虫实战 requests模块 Python实现抓取头条街拍美图

时间:2021-03-27 15:31:05

相关推荐

python爬虫实战 requests模块 Python实现抓取头条街拍美图

前言

利用Python爬取的是今日头条中的街拍美图。废话不多说。

让我们愉快地开始吧~

开发工具

Python版本:3.6.4

相关模块:

re;

requests模块;

以及一些Python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

详细浏览器信息

获取文章链接相关代码:

importrequestsimportjsonimportreheaders={'user-agent':'Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/55.0.2883.87Safari/537.36'}defget_first_data(offset):params={'offset':offset,'format':'json','keyword':'街拍','autoload':'true','count':'20','cur_tab':'1','from':'search_tab'}response=requests.get(url='/search_content/',headers=headers,params=params)try:response.raise_for_status()returnresponse.textexceptExceptionasexc:print("获取失败")returnNonedefhandle_first_data(html):data=json.loads(html)ifdataand"data"indata.keys():foritemindata.get("data"):yielditem.get("article_url")复制代码

这里需要提一下requests模块的报错,在response对象上调用 raise_for_status()方法,如果下载文件出错,会抛出异常,需要使用 try 和 except 语句将代码行包裹起来,处理这一错误,不让程序崩溃。

另外附上requests模块技术文档网址:http://cn.python-/zh_CN/latest/

获取图片链接相关代码:

defget_second_data(url):ifurl: try:reponse=requests.get(url,headers=headers)reponse.raise_for_status()returnreponse.textexceptExceptionasexc:print("进入链接发生错误")returnNonedefhandle_second_data(html):ifhtml:pattern=pile(r'gallery:JSON.parse\((.*?)\),',re.S)result=re.search(pattern,html)ifresult:imageurl=[]data=json.loads(json.loads(result.group(1)))ifdataand"sub_images"indata.keys():sub_images=data.get("sub_images")images=[item.get('url')foriteminsub_images]for image in images:imageurl.append(images)returnimageurlelse:print("havenoresult")复制代码

获取图片相关代码:

defdownload_image(imageUrl):forurlinimageUrl:try:image=requests.get(url).contentexcept:passwithopen("images"+str(url[-10:])+".jpg","wb")asob:ob.write(image)ob.close()print(url[-10:]+"下载成功!"+url)defmain():html=get_first_data(0)forurlinhandle_first_data(html):html=get_second_data(url)ifhtml:result=handle_second_data(html)ifresult:try:download_image(result)exceptKeyError:print("{0}存在问题,略过".format(result))continueif__name__=='__main__':main()复制代码

最后下载成功

查看详情

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。