Python2--糗百图片下载
来源:互联网 发布:淘宝三哥家店名叫什么 编辑:程序博客网 时间:2024/05/16 07:38
在实现内容的爬取后,我想实现用户头像的下载。其实只需要在前一部分的代码中再加上关于图片url的链接即可。
第一个实例
- 图片url获取
def get_data(html ): final = [] pictures = []存放图片url bs = BeautifulSoup(html, "html.parser") body = bs.body content_left = body.find(id = 'content-left') #找到该页总框 contents = content_left.find_all('div',class_ = 'article block untagged mb15')#找到所有内容框 for content in contents: #对每个故事进行遍历 temp = [] author = content.find('div',class_='author clearfix') picture = author.find('img')#找到img标签 picture_src = picture.get('src')#获取图片url pictures.append(picture_src)#添加到图片list中 user_name = content.find("h2").string temp.append(user_name) data = content.find(class_ = 'content') story = data.find('span').get_text() temp.append(story) numbers = content.find_all('i', class_ = 'number') good = numbers[0].string + '好笑' temp.append(good) comment = numbers[1].string + '评论' temp.append(comment) temp.append(picture_src) final.append(temp) return final,pictures#返回data和pictures的list
这里返回了一个含有所有头像url的list,然后根据这些url将图片下载到本地。
- 头像下载
def download_pic(pictures): count = 1#picture命名 if not os.path.exists('pic'):#如果不存在pic文件夹,则创建一个名为pic的文件夹 os.makedirs('pic') for picture in pictures:#对list中的url进行循环下载 if picture == '/static/images/thumb/anony.png?v=b61e7f5162d14b7c0d5f419cd6649c87':#如果头像是默认头像则跳过 print("静态图片") continue else: try: r = requests.get(picture)#获取头像 except BaseException as e: print("图片下载失败", e) time.sleep(random.choice(range(30, 80))) else: filename = str(count) + '.jpg'#给头像命名 path = "pic/" + filename f = open(path, 'wb')#保存头像 f.write(r.content) print(count) count = count + 1
- 主函数
if __name__ == '__main__': url ='http://www.qiushibaike.com/' result,picture = get_data(url) write_data(result, 'qiubai.csv') download_pic(picture)
- 结果
最后可以得到用户头像和想获取的信息。
0 0
- Python2--糗百图片下载
- 图片下载
- 图片下载
- 图片下载
- 图片下载
- 图片下载
- python2
- Python2
- Python2
- python2
- python2
- Python2
- python2
- 图片下载(仅限图片下载)
- struts2图片下载
- IOS 图片下载
- 图片下载保存
- 图片下载ImageFromWeb
- Reverse LinkedList
- Reverse Linked List
- Integer Vulnerability
- Easy 101题 Symmetric Tree
- Node.js 文档v4.6.1翻译 (1) 断言测试 assert
- Python2--糗百图片下载
- Using Darshan On BlueWaters
- 浏览器兼容问题(实战干货)
- mac解决python连接MySQL,import MySQLdb后,出现no suitable image... but wrong architecture
- Python3--翻页
- 第十四章 个人渣翻译 spf13插件---NERDCommenter 使用教程
- Medium 277题 Find the Celebrity
- 1.第一章,数据的处理
- Python4--登录知乎