来和伯衡君一起快速入门Python爬虫——Beautifulsoup篇(四)

已收录   阅读次数: 973
2021-02-0821:07:16 发表评论
摘要

通过之前的三篇文章,已经对python爬虫和Beautifulsoup库有了进一步了解,这次咱们继续探索,爬取网站的图片,还是以本站为例,爬取本站首页的图片,并且加了定时器,减缓服务器压力,以免因服务器原因导致服务器崩溃,分享给大家……

分享至:
来和伯衡君一起快速入门Python爬虫——Beautifulsoup篇(四)

开篇寄语

通过之前的三篇文章,已经对python爬虫和Beautifulsoup库有了进一步了解,这次咱们继续探索,爬取网站的图片,还是以本站为例,爬取本站首页的图片,并且加了定时器,减缓服务器压力,以免因服务器原因导致服务器崩溃,分享给大家。

前情提要

官方库指导文档

内容详情

需要将图片保存到工作的python文件夹内,新建一个文件夹以保存批量爬取的图片,所以需要引入os这个库,同时添加定时器,那么time这个库也要引入,所以开头就这样写,引入四个库:

import os
import time
import requests
from bs4 import BeautifulSoup

首先是查看网站的源码,使用下面的代码:

import os
import time
import requests
from bs4 import BeautifulSoup

url = "https://www.luckydesigner.space"
req = requests.get(url)
soup = BeautifulSoup(req.text, "lxml")
print(soup.pretiffy())

回车后,就会看到本站首页的源代码,通过观察,发现这些图片都在<img>标签内,src就是图片地址,那么就先将所有的图片链接都放置在一个列表里面:

import os
import time
import requests
from bs4 import BeautifulSoup

url = "https://www.luckydesigner.space"
req = requests.get(url)
soup = BeautifulSoup(req.text, "lxml")
images = soup.find_all("img")
lst = []
for i in images:
    lst.append(i.attrs["src"])
print(lst)

想要爬取所有图片到本地,保存在一个文件夹,那么就需要用到os模块来创建,并利用正则表达式来获取正确的图片地址,还有就是2秒爬取一下,防止网站崩溃:

import os
import re
import time
import requests
from bs4 import BeautifulSoup

url = "https://www.luckydesigner.space"
req = requests.get(url)
soup = BeautifulSoup(req.text, "lxml")
images = soup.find_all("img")
lst = []
for i in images:
    lst.append(i.attrs["src"])
dir_name = "iwate"
if not os.path.exists(dir_name):
    os.mkdir(dir_name)
for img in lst:
    time.sleep(2)
    picture_name = re.findall("\w.+[jpg]", img.split('/')[-1])[0]
    reponse = requests.get(img)
    with open(dir_name+'/'+picture_name,'wb') as f:
        f.write(reponse.content)

在编辑器运行后,就会看到陆陆续续的图片被爬取下来,并放在一个名为“iwate”的文件夹内,如下图所示:

来和伯衡君一起快速入门Python爬虫——Beautifulsoup篇(四)

打开对应的文件夹,就可以看到所爬取的图片都在里面了。

来和伯衡君一起快速入门Python爬虫——Beautifulsoup篇(四)

之后,伯衡君就在iPad上使用Carpets这款App进行实战,爬取豆瓣电影网站首页的电影海报图片,代码如下:

import os
import time
import requests
from fake_useragent import UserAgent
from bs4 import BeautifulSoup

ua = UserAgent()
headers = {"User-Agent":ua.random}
url = "https://movie.douban.com/"
req = requests.get(url, headers=headers)
soup = BeautifulSoup(req.text, "lxml")
chi = soup.find_all("img")
lst = []
for i in chi[0:-4]:
    lst.append(i.attrs["src"])
dir_name = "doubanView"
if not os.path.exists(dir_name):
    os.mkdir(dir_name)
for i in lst:
    time.sleep(2)
    image_name = i.split("/")[-1]
    response = requests.get(i)
    with open(dir_name+"/"+image_name, "wb") as f:
        f.write(response.content)

点击运行后,这样就会在Carpets同名文件夹下生成一个名为“doubanView”的文件夹,打开后,里面就是爬取到的图片了,如下图所示:

来和伯衡君一起快速入门Python爬虫——Beautifulsoup篇(四)

这样一来,爬取一些需要的图片可以省时省力不少。

  • 我的微信
  • 微信扫一扫加好友
  • weinxin
  • 我的微信公众号
  • 扫描关注公众号
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: