今天学习了用beautifulsoup来爬取信息,并完成了爬取一个网站的图片并下载到文件中
import requests
from bs4 import BeautifulSoup
import time
url = 'https://www.umei.cc/bizhitupian/weimeibizhi/'
resp = requests.get(url)
resp.encoding = 'utf-8' #处理乱码
#print(resp.text)
main_page = BeautifulSoup(resp.text, "html.parser") #告诉它我就是一个html
alist = main_page.find("div",class_="TypeList").find_all("a") #第一次缩小范围,找到所有的a标签
#print(alist) #可以得到所有的a标签,但我们只要其中一个
for a in alist:
href = a.get('href') #直接通过get可以获得标签中href属性的值(所有的a标签)
#拿到子页面(href属性值就是子页面地址)的源代码
child_page_response = requests.get(href)
child_page_response.encoding = 'utf-8'
child_text = child_page_response.text
#从子页面中拿到图片的下载途径
child_page = BeautifulSoup(child_text,'html.parser')
p = child_page.find("p",align = "center")#p标签中align的值为center的地方开始定位找
img = p.find("img")#从p标签里面再找,p标签里就一个img
#print(img.get("src")) #拿到了所以图片的下载路径
src = img.get("src") #通过get来获得想要的属性src的值
#下载图片
img_resp = requests.get(src)
img_name = src.split("/")[-1]#拿到url中的最后一个、以后的内# 容
with open("img/"+img_name,mode="wb") as f:
f.write(img_resp.content) #图片内容写入文件(content其实是字节)
time.sleep(1)