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

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

2017-08-14 20:17 1011 查看
本文主要涉及一些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')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息