使用Selenium+firefox抓取网页指定firefox_profile后的问题

from: https://blog.csdn.net/chufazhe/article/details/51145834

摘要:
在使用selenium和firefox抓取网页指定firefox_profile后遇到问题,生成的日志文件太大直接导致C盘资源耗尽,火狐浏览器直接就停止工作了。

一、环境
windows2008 server(尴尬,C盘空间还剧小)

python 3.4

selenium + firefox

二、代码情况
利用selenium 调用Firefox内核爬取网站

sFirefoxProfile ='C:\\Users\\username\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\2alxrl56.default' # firefox 配置文件路径
fProfile= FirefoxProfile(sFirefoxProfile) # Firefox配置文件,如果不设置这个也可能会被认为是爬虫
driver = webdriver.Firefox(fProfile)

抓取一段时间之后发现爬虫不再抓取网页,火狐停止工作,发现是C盘用户路径下面生成了大量的临时文件,其中日志文件特别大。

C:\Users\username\AppData\Local\Temp\3\tmpuuvium\webdriver-py-profilecopy

爬虫每次启动之后都会从指定的Firefox配置文件路径复制到临时目录中,并且开始生成日志文件。

一开始我希望能够不让爬虫启动的时候都重新生成临时目录,直接使用上次复制后得到的配置文件,但是经过检索并没有发现可行的办法。在检索过程中发现了selenium.webdriver.firefox.firefox_profile 的<a target=_blank href="https://selenium.googlecode.com/git/docs/api/py/_modules/selenium/webdriver/firefox/firefox_profile.html">源代码</a>。发现并没有类似的方法,而且找到了每次生成临时目录的相关代码。

class FirefoxProfile(object):
ANONYMOUS_PROFILE_NAME = "WEBDRIVER_ANONYMOUS_PROFILE"
DEFAULT_PREFERENCES = None

def __init__(self, profile_directory=None):
"""
Initialises a new instance of a Firefox Profile
:args:
- profile_directory: Directory of profile that you want to use.
This defaults to None and will create a new
directory when object is created.
"""
if not FirefoxProfile.DEFAULT_PREFERENCES:
with open(os.path.join(os.path.dirname(__file__),
WEBDRIVER_PREFERENCES)) as default_prefs:
FirefoxProfile.DEFAULT_PREFERENCES = json.load(default_prefs)

self.default_preferences = copy.deepcopy(
FirefoxProfile.DEFAULT_PREFERENCES['mutable'])
self.native_events_enabled = True
self.profile_dir = profile_directory
self.tempfolder = None
if self.profile_dir is None:
self.profile_dir = self._create_tempfolder()
else:
self.tempfolder = tempfile.mkdtemp()
newprof = os.path.join(self.tempfolder, "webdriver-py-profilecopy")
shutil.copytree(self.profile_dir, newprof,
ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock"))
self.profile_dir = newprof
self._read_existing_userjs(os.path.join(self.profile_dir, "user.js"))
self.extensionsDir = os.path.join(self.profile_dir, "extensions")
self.userPrefs = os.path.join(self.profile_dir, "user.js")


可以发现在设置FirefoxProfile的过程就会生成临时目录,并且会完成一次拷贝。而生成临时目录是通过tempfile的mkdtemp()实现的。
我去看了一下tempfile的mkdtemp()方法:

tempfile.mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])

在未指定dir的情况下,将根据系统环境变量TMPDIR, TEMP或者TMP的设置来保存临时文件。由于不能在FireProfile的代码上改动,所以问题变成设置环境变量TMPDIR。

# 设置环境变量
os.environ['TMPDIR']=os.path.join(os.path.abspath('.'), 'profile')
这样,每次爬虫每次启动都会在当前目录的profile目录下生成临时文件。尽管解决方案不够理想,但是足够让爬虫继续运行下去了。
也许直接在Selenium的源代码直接修改后重新编译会更省事,留待以后尝试吧。

注:

python环境变量的设置

1、os.environ['环境变量名称']='环境变量值' #其中key和value均为string类型
2、os.putenv('环境变量名称', '环境变量值')


获取系统环境变量
1、os.environ['环境变量名称']
2、os.getenv('环境变量名称')


以上方法,推荐用os.environ,因为使用os.putenv()并不会真正改变os.environ字典里面的环境变量,即某些平台无效,但是使用os.environ有一个潜在的隐患:在一些平台上,包括FreeBSD和Mac OS X,修改environ会导致内存泄露。设置的环境变量只存在于当前的python shell中(设置成功后用print os.environ['环境变量名称']或printos.getenv('环境变量名称') 查看)。

参考资料:
1. FireProfile源代码:

https://selenium.googlecode.com/git/docs/api/py/_modules/selenium/webdriver/firefox/firefox_profile.html

2. tempfile的相关方法:

http://www.cnblogs.com/captain_jack/archive/2011/01/19/1939555.html

3. python设置获取环境变量的方法:

http://aurorawu.lofter.com/post/18f005_6fd653

猜你喜欢

转载自www.cnblogs.com/pythonClub/p/10447351.html