参考网站:http://zmister.com/archives/98.html
目标:Python用selenium爬取某位幸运观众的QQ空间说说的文字内容,发表时间。
(1)源代码如下:



(2)运行结果如下:

(3)关键问题:
①关与所调用的浏览器
FireFox:
driver = webdriver.Firefox(executable_path="D:\Program Files\geckodriver\geckodriver.exe")
调用简单,运行速度较慢,关键是莫名出现bug

关于这个问题,百度过后并未找到解决方案。根据搜索结果,应该是FireFox升级以后与selenium版本不兼容出现的bug。
Chrome:
chromedriver = "C:/Users/Windows/AppData/Local/Google/Chrome/Application/chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
调用略复杂?运行速度较FireFox快,没有bug
phantomjs:
driver= webdriver.PhantomJS(executable_path=r"D:\Program Files\phantomjs-2.1.1-windows\bin\phantomjs.exe")
一开始并没有在路径前加r,一直报错提示要把phantomjs添加到PATH中。然而我已经添加过了,还在代码中直接指明路径。经过百度,是windows指明路径时需在路径前加r。

之前指明FireFox和Chrome的路径也没有加r,也没有因此报错。不知道phantomjs为什么要加r
②关于找不到frame

----在第一页中系统报告找不到上述frame。
添加等待时间后,问题得到解决。
----在第二页时,即使添加等待时间后,也找不到上述frame。
需要在查找该frame前返回到default content

③爬取发表说说的时间
----找不到元素
一开始定位元素的方式是:stime = driver.find_elements_by_class_name("c_tx c_tx3 goDetail")
这是根据源代码直接复制下来的class属性。然而系统报错,表示属性名不合法。
经过百度,原来 是selenium所查找元素的class_name不能含有空格。因此只能用另外一种表示:
#stime = driver.find_elements_by_css_selector(".c_tx.c_tx3.goDetail")
爬取成功
----说说内容与时间不对应

当用户转发其他人的说说时,爬取下来的时间居然是所转发说说的发表时间。原因是,该元素的名称和目标元素名称一致。因此换用别的方式定位元素:
stime = driver.find_elements_by_xpath("//div[@class='box bgr3']/div[@class='ft']/div[@class='info']/span[@class='c_tx3']/a")
总结:百度真是个好东西
源代码: https://github.com/caiyingyi/qq
网友评论