py爬虫,上面都已经做了备注,
import requests
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
#用来获取网页
def get_one_page(url):
try:
reponse=requests.get(url)
if reponse.status_code==200: #请求成功,返回请求的html内容
# print("success")
return reponse.text
return None
except RequestException: #请求不成功,返回空值
return None
#保存数据
def save_data(data,name,title):
file_name='./page/'+title+ str(name) #存储的文件路径
with open(file_name,'wb')as f: #将文件写入存储路径
f.write(data)
#下载网页图片
def downlodingImage(url):
if url!=None:
response=requests.get(url) #向图片地址发送请求
return response.content #下载图片
#获取网页具体内容
def main():
url='https://699pic.com/tupian/qizhimeinv.html' #摄图网地址
html=get_one_page(url) #得到摄图网的html
soup=BeautifulSoup(html,'lxml') #将html整合到Beatifulsoup中
ds=soup.select('.swipeboxEx .list a img') #获取.swipeboxEx .list a img选择器中所有的img标签
for index in ds:
# print(index) 遍历输出img标签的值
dict={
'标题':index.attrs['alt'], #获取img标签中的alt属性的值
'路劲':"https:"+index.attrs['data-original'], #获取img标签中的data-original值并且加上https:构成下载地址
'name':index.attrs['data-original'].split('/')[5] #将data-original中的属性值以‘/’分割成若干段,5取最后一段
}
data=downlodingImage(dict['路劲']) #根据下载地址下载
save_data(data,dict['name'],dict['标题']) #将下载下来的数据保存到本地
print('success')
# print(soup.prettify())
if __name__ == '__main__':
main()