您的位置:首页 > 编程语言 > Python开发

python爬虫:利用Requests和BeautifulSoup爬取百度贴吧多页图片

2019-02-23 22:18 1286 查看
[code]import requests
from bs4 import BeautifulSoup
import os
os.chdir(r'D:\liqin')
def get_page(url):
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
response = requests.get(url, headers=headers)
if response.status_code == 200:  # 页面正常响应
return response.text  # 返回页面源代码
return None
def get_data():
for i in range(1,6):
url = 'http://tieba.baidu.com/p/4718154281?pn=' + str(i)
html = get_page(url)
soup = BeautifulSoup(html, 'html.parser')#html.parser是解析器
imgs = soup.find_all('img',attrs = {'class':'BDE_Image'})#从响应的数据中找到class是'BDE_Image'的数据
for img in imgs:
img_src = img.get('src')#得到img的url
img_content=requests.get(img_src).content#得到这个url下的内容content,应该是二进制的
filename=img_src.split('/')[-1]
with open(filename, 'wb') as f:
f.write(img_content)
if __name__ =='__main__':
get_data()

这是一个简单的Python爬虫,由于本人还处于爬虫菜鸟阶段,有什么不正确的地方还请各位大神指正,大家一起学习进步

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: