基于Headless浏览器来访问当当页面商品信息--代码示例

依赖库说明

selenium: 兼容不同浏览器的WebDriver
PhantomJS: 著名的无头浏览器,不幸的是最近maintainer放弃继续支持维护了,真是一件悲伤的事情。
开发语言: Python 3.6

功能描述

从当当商城中爬取某个商品的价格和名称。这里尝试查找”非暴力沟通“的图书信息,输出价格和命名。

代码示例

  # -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 14:41:01 2018

@author: chenjunfeng
"""

from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
import pandas as pd
import re
from selenium.webdriver.common.keys import Keys

driver = webdriver.PhantomJS(executable_path=r'D:/Program Files/phantomjs-2.1.1-windows/bin/phantomjs')

url='http://www.dangdang.com/'

driver.get(url)

input_node=driver.find_element_by_xpath('//*[@id="key_S"]')

input_node.send_keys(r"非暴力沟通")
input_node.send_keys(Keys.ENTER)
# wait for a second
driver.implicitly_wait(1)

title_path = r'//*[@id="p23807861"]/p[1]/a/font'
price_path = r'//*[@id="p23807861"]/p[3]/span[1]'

title = driver.find_element_by_xpath(title_path).text
price = driver.find_element_by_xpath(price_path).text

print("title:" + title + ", price:" + price)

代码说明:
1. 这里默认使用的phantomjs的路径是内置写死的,大家可以自行修改即可。
2. Firefox/Chrome中使用的xpath路径是不一样的,建议使用chrome
3. 在这里使用的web element的节点是直接写死的,大家可以参考使用相对xpath来进行大范围的查找和使用

## 总结
基于headless浏览器非常强大,从此没有不能爬的数据了……

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/80986551