python3爬虫爬取煎蛋网妹纸图片(下篇)2018.6.25有效
2024-08-28 12:39:51
分析完了真实图片链接地址,下面要做的就是写代码去实现了。想直接看源代码的可以点击这里
大致思路是:获取一个页面的的html---->使用正则表达式提取出图片hash值并进行base64解码--->将解码得到的结果进行拼接替换,得到原始图片地址--->对图片地址进行请求,对返回的content进行保存--->扩展到多个页面的爬取
首先请求一个页面,我们以http://jandan.net/ooxx/page-47#comments也就是首页为例(网站会不时变动,下次可能就不是这个page值了)
def get_page_html(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except Exception as e:
print(e)
然后使用正则表达式提取图片hash值
def get_real_img(html):
pattern = re.compile('<span class="img-hash">(.*?)</span>')
imgs_hash = re.findall(pattern, html)
for img_hash in imgs_hash:
yield base64_decode(img_hash)
使用base64解码
def base64_decode(img_hash):
img_hash = base64.b64decode(img_hash)
return img_hash
对图片进行请求
def get_img_content(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
save_img(url, response.content)
return None
except Exception as e:
print(e)
对图片进行保存
def save_img(url, content):
root = 'E://jandan/'
path = root + url.split('/')[-1]
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
with open(path, 'wb') as f:
f.write(content)
print('保存成功', url)
定义一个主函数,这里我传入了一个参数i,也就是页面号。另外加了一个睡眠,在每一次对页面进行请求获取内容前停留一段时间,防止频繁爬取被封ip。
def main(i):
start_url = 'http://jandan.net/ooxx/page-{}#comments'.format(i)
time.sleep(random.random() * random.randint(1, 10))
html = get_page_html(start_url)
for result in get_real_img(html):
url_split = result.decode('utf-8').split('/')
real_img_url = 'http://{}/{}/{}'.format(url_split[-3], 'large', url_split[-1])
get_img_content(real_img_url)
最后写一个程序入口:
if __name__ == '__main__':
start_page = 1
end_page = 47
pool = Pool()
pool.map(main, [i for i in range(start_page, end_page + 1)])
最后的最后我们看一下成果:
好了,关于煎蛋的话题就到这里。完整代码可以点击查看
最新文章
- C# 操作excel单元格居中
- 运行Shell脚本的几种方式解析
- [学习笔记]坚果云网盘,SVN异地代码管理
- redis sentinel基本命令与参数
- 细说.NET中的多线程 (三 使用Task)
- maven的入门hello world
- mount挂载
- POJ 3233 矩阵乘法
- grails的插件
- C++封装SQLite实例&;lt;三&;gt;
- NET Framework 4.5 五个新特性
- AR9531的mac地址
- yii2.0使用ActionForm创建表单
- P4语言编程快速开始 实践二
- Vtiger CRM 几处SQL注入漏洞分析,测试工程师可借鉴
- JDK1.8源码(三)——java.util.HashMap
- mysql常见操作语句,建表,增删改查
- mac电脑设置USB键盘按键方法,设置多显示屏镜像显示器的方法
- shell数组应用
- [js]ext.js探索