【Python3.6爬虫学习记录】(四)爬取百度贴吧某帖子内容及图片

本文主要涉及一些BeautifulSoup的的用法
在其中加入循环可以爬取更多帖子

# 尝试
# 花瓣网的图片貌似架在第三方,无法这样简单的下载--未成功
# 百度图片 --目测动态网址--太难,未成功
# 爬取百度贴吧帖子图片及帖子标题及内容
# soup.find_all()得到的所有符合条件的结果和soup.select()一样都是列表list,
# 而soup.find()只返回第一个符合条件的结果,
# 所以soup.find()后面可以直接接.text或者get_text()来获得标签中的文本。
from bs4 import BeautifulSoup
import requests
import lxml
# 百度贴吧
url = 'https://tieba.baidu.com/p/3572475102'
html = requests.get(url).content
soup = BeautifulSoup(html,'lxml')
# 百度贴吧
article = soup.find('div',class_="left_section")
# 在正文标签里面找图片链接
article1 = article.find_all()
#百度贴吧
images = article.find_all('img',class_="BDE_Image")
# 下载图片
 i=0
 print('Start')
 for image in images:
     image_url = image["src"]
     # 检查搜索的URL
     # print(imge_url)

     with open('图片8-13\\'+str(i)+'.jpg','wb') as f:
         try:
             re = requests.get(image_url).content
             f.write(re)
             print(str(i) + '.jpg is downloading')
             i+=1
         except Exception:
             print('Something is wrong!')

 print('Finish')

# 百度贴吧帖子标题及帖子文字内容
title = article.find('div',class_="core_title_wrap_bright clearfix")
# 注意用find_all搜索得到的是一个列表,不能直接用find查找其中的标签
endTitle=title.find('h3')
difs = article.find_all('div',class_="d_post_content j_d_post_content ")
print('Start')
# 创建文件写在循环内部会导致前面写入的被覆盖
with open(str(endTitle["title"])+'.txt', 'w') as f:
    for dif in difs:
        try:
            f.write(str(dif.get_text())+'\n')
        except Exception:
            print('Something is wrong')
print('Finish')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值