紧接着上文,继续探索
headers
在不断尝试过程中,遇到了一个问题:有时候抓回来的网页会没有相关信息。猜测是因为 User-Agent(默认是phantomJS),那就尝试增加 headers
这篇文章 https://www.zhihu.com/question/35547395 提供了解决方案:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (user_agent)
driver = webdriver.PhantomJS(desired_capabilities=dcap)
下载图片
在上文中,已经获取到图片链接,那么下一步就是下载下来咯(这才是目的嘛)。
直接使用selenium ?
一开始考虑直接使用 driver.get(url) 来下载,但这个方法还是会获取html代码,并不能将图片数据下载。urllib 库
使用 urlllib.urlopen(url) 可以获取到图片数据,然后通过 IO 保存到文件即可。然而存在一个问题是,没搜到该库如何添加 headers(因为网站服务器会进行识别),所以需要寻找替代方案。
(如果有童鞋知道该库怎么添加 headers,请给我留言评论,谢谢!)urllib2 库
跟 urllib 库相似,但还是存在挺大的区别点,对这个感兴趣的童鞋请自行搜索。
# 来自:http://www.jianshu.com/p/6094ff96536d
with open('name.jpg', 'wb') as f:
headers = {'User-Agent': user_agent}
request = urllib2.Request(img_src if img_src.startswith('http') else 'http:'+img_src, None, headers)
response = urllib2.urlopen(request)
f.write(response.read())
- requests 库
一个好用的第三方库,如果不了解的童鞋,可参考此网页
# https://segmentfault.com/q/1010000007024942?_ea=1212676
with open('name.jpg', 'wb') as f:
headers = {'User-Agent': user_agent}
ir = requests.get(img_src if img_src.startswith('http') else 'http:'+img_src, headers=headers, stream=True)
if ir.status_code == 200:
f.write(ir.content)
第二版结果
下载首页的所有图片
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-18 21:29:56
# @Author : kk (zwk.patrick@foxmail.com)
# @Link : blog.csdn.net/PatrickZheng
# @Version : $Id$
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from bs4 import BeautifulSoup
import requests, urllib2
import os.path
# 有时候网站服务器会拒绝响应
while True:
# 设置 Headers
# https://www.zhihu.com/question/35547395
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (user_agent)
driver = webdriver.PhantomJS(executable_path='D:\workplace\spider\phantomjs-2.1.1-windows\phantomjs.exe', desired_capabilities=dcap)
driver.get('https://www.taobao.com/markets/mm/mmku')
soup = BeautifulSoup(driver.page_source, 'lxml')
# 每个MM的展示是放在 属性class=cons_li的div中
cons_li_list = soup.select('.cons_li')
lenOfList = len(cons_li_list)
print lenOfList
if lenOfList == 0:
continue
for cons_li in cons_li_list:
name = cons_li.select('.item_name')[0].get_text().strip('\n')
print name
img = cons_li.select('.item_img img')[0]
img_src = img.get('src')
if img_src is None:
img_src = img.get('data-ks-lazyload')
print img_src
filename = name + os.path.splitext(img_src)[1]
with open(filename, 'wb') as f:
headers = {'User-Agent': user_agent}
# urllib.urlopen 好像不支持添加 headers
# 换用 requests 库
# https://segmentfault.com/q/1010000007024942?_ea=1212676
''' ir = requests.get(img_src if img_src.startswith('http') else 'http:'+img_src, headers=headers, stream=True) if ir.status_code == 200: f.write(ir.content) '''
# urllib2 可以添加 headers
# http://www.jianshu.com/p/6094ff96536d
request = urllib2.Request(img_src if img_src.startswith('http') else 'http:'+img_src, None, headers)
response = urllib2.urlopen(request)
f.write(response.read())
driver.close()
print 'done.'
break
上述源码放到 Patrick-kk的github, 一起学习交流