本帖最后由 xandy 于 2016-10-20 10:27 编辑

1. 引言

上一篇《为编写网络爬虫程序安装Python3.5》中测试小例子对静态网页做了一个简单的采集程序,而动态网页因为需要动态加载js获取数据,所以使用urllib直接openurl已经不能满足采集的需求了。这里我们使用selenium库,通过它我们可以很简单的使用浏览器来为我们加载动态内容,从而获取采集结果。

在很多案例中,Selenium与PhantomJS搭配采集动态网页内容(可以参看我以前发表的案例文章),直接与Firefox或者Chrome搭配,可以应对一些更加复杂的采集情形,比如,在防爬方面,直接驱动普通浏览器更不容易被识别成爬虫。所以,本文讲解与Firefox搭配,开发难度并没有增加。

Python版本:Python3

2. 安装selenium库

使用快捷键win + R或右键开始选择运行,输入cmd回车,打开命令提示符窗口,输入命令:pip install selenium
python24_1.png


3. 以亚马逊商品为例的一个简单爬虫

3.1 引入Gooseeker规则提取器模块gooseeker.py(下载地址: https://github.com/FullerHua/gooseeker/tree/master/core), 自定义存放目录,这里为E:\demo\gooseeker.py

引入GooSeeker规则提取器,就省去手工编写XPath或者正则表达式的麻烦,用直观标注的方式自动生成采集规则后,通过API加载和使用采集规则。操作过程请参看《1分钟快速生成用于网页内容提取的xslt》。

下面的代码就是使用了API,所以看不到冗长的XPath和正则表达式规则,代码中的API key和抓取规则名可以直接使用,这是公共的测试用的规则。

3.2 在提取器模块gooseeker.py同级目录下创建一个.py后缀文件,如这里为E:\Demo\second.py,再以记事本打开,敲入代码:

  1. # -*- coding: utf-8 -*-
  2. # 使用gsExtractor类的示例程序
  3. # 以webdriver驱动Firefox采集亚马逊商品列表
  4. # xslt保存在xslt_bbs.xml中
  5. # 采集结果保存在result-2.xml中

  6. import os
  7. import time
  8. from lxml import etree
  9. from selenium import webdriver

  10. from gooseeker import GsExtractor

  11. #驱动火狐
  12. driver = webdriver.Firefox()
  13. # 访问并读取网页内容
  14. url = "https://www.amazon.cn/b/ref=s9_acss_bw_ct_refTest_ct_1_h?_encoding=UTF8&node=658810051&pf_rd_m=A1AJ19PSB66TGU&pf_rd_s=merchandised-search-5&pf_rd_r=WJANDTHE4NFAYRR4P95K&pf_rd_t=101&pf_rd_p=289436412&pf_rd_i=658414051"
  15. #开始加载
  16. driver.get(url)
  17. #等待2秒,更据动态网页加载耗时自定义
  18. time.sleep(2)
  19. # 获取网页内容
  20. content = driver.page_source.encode('utf-8')
  21. # 获取docment
  22. doc = etree.HTML(content)

  23. # 引用提取器
  24. bbsExtra = GsExtractor()   
  25. bbsExtra.setXsltFromAPI("31d24931e043e2d5364d03b8ff9cc77e", "亚马逊图书_test") # 设置xslt抓取规则
  26. result = bbsExtra.extract(doc)   # 调用extract方法提取所需内容

  27. # 当前目录
  28. current_path = os.getcwd()
  29. file_path = current_path + "/result-2.xml"

  30. # 保存结果
  31. open(file_path,"wb").write(result)

  32. # 打印出结果
  33. print(str(result).encode('gbk','ignore').decode('gbk'))
复制代码

3.3 执行second.py,打开命令提示窗口,进入second.py文件所在目录,输入命令 :python second.py 回车


注:这里是以驱动Firefox为例,所以需要安装Firefox,若未安装可以去往Firefox官网下载安装


python24_2.png


python24_3.png


3.4 查看保存结果文件,进入second.py文件所在目录,找到名称为result-2的xml文件

python24_4.png


4. 总结

安装selenium,由于网络原因失败了一次,后面再次安装时才成功,如果碰到多次超时而安装失败,可以尝试连接vpn后再使用pip命令安装。

下一篇《快速制作规则并获取提取器api》将会讲解:快速的将一个网页结构生成规则并通过规则Api方式得到需要采集的结果。

5. 文档修改历史

2016-09-29:V1.0

6. 集搜客GooSeeker开源代码下载源

GooSeeker开源Python网络爬虫GitHub源




举报 使用道具
| 回复

共 7 个关于本帖的回复 最后回复于 2017-7-27 12:28

shenzhenwan10 金牌会员 发表于 2016-9-30 11:45:49 | 显示全部楼层
这个好,去掉注释部分和空行,其它代码就大概十几行
举报 使用道具
dengxu119 新手上路 发表于 2016-11-25 09:26:35 | 显示全部楼层
运行报错信息如下:Traceback (most recent call last):
  File "second.py", line 15, in <module>
    driver = webdriver.Firefox()
  File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\firefox\w
ebdriver.py", line 145, in __init__
    keep_alive=True)
  File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\remote\we
bdriver.py", line 92, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\remote\we
bdriver.py", line 179, in start_session
    response = self.execute(Command.NEW_SESSION, capabilities)
  File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\remote\we
bdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\remote\er
rorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Missing 'marionetteProto
col' field in handshake
elenium.common.exceptions.WebDriverException: Message: Missing 'marionetteProto
col' field in handshake
百度说是因为selenium3.01和firefox38.8驱动问题请问如何解决??
举报 使用道具
abc965432 新手上路 发表于 2017-6-20 14:13:13 | 显示全部楼层
为什么我照着例子做的,但数据没抓下来啊?

D:\\python\demo>python second.py
<?xml version="1.0"?>
<亚马逊图书/>


只抓了个头标签,没抓到具体的数据。
举报 使用道具
shenzhenwan10 金牌会员 发表于 2017-6-20 17:27:41 | 显示全部楼层
由于亚马逊页面结构改变, 提取器失效了
现在已经更新了提取器, 你可以再试试
举报 使用道具
大锅方便面 新手上路 发表于 2017-7-13 21:30:26 | 显示全部楼层
请教一下运行后出现这样的问题是什么原因?
SyntaxError: (unicode error) 'utf-8' code can't decode byte Oxd1 in position 0: invalid continuation byte.
谢谢
举报 使用道具
shenzhenwan10 金牌会员 发表于 2017-7-14 15:25:34 | 显示全部楼层
大锅方便面 发表于 2017-7-13 21:30
请教一下运行后出现这样的问题是什么原因?
SyntaxError: (unicode error) 'utf-8' code can't decode byte ...

你是在什么环境下运行的? 如果是windows的CMD窗口, 可能是字符编码不匹配的问题
你把最后的那行print注释掉


举报 使用道具
mingdongtianxia 中级会员 发表于 2017-7-27 12:28:45 | 显示全部楼层
没有抓出数据,这是咋回事啊,提示如下,技术大哥给看看呀?

Traceback (most recent call last):
  File "D:\Program Files\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "D:\Program Files\Python35\lib\subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
  File "D:\Program Files\Python35\lib\subprocess.py", line 1220, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] 系统找不到指定的文件。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "second.py", line 15, in <module>
    driver = webdriver.Firefox()
  File "D:\Program Files\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 142, in __init__
    self.service.start()
  File "D:\Program Files\Python35\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
举报 使用道具
您需要登录后才可以回帖 登录 | 立即注册

精彩推荐

  • Gephi社会网络分析-马蜂窝游记文本分词并同
  • Gephi社会网络分析-基于马蜂窝游记文本以词
  • 知乎话题文本根据词语间距筛选后生成共词矩
  • 马蜂窝游记文本分词后以词语间距为筛选条件
  • 学习使用apriori算法挖掘关联关系

热门用户

GMT+8, 2024-3-28 18:04