去发现生活中的美好,记录生活中的点点滴滴

python+selenium库的基本使用

python admin 1140℃
selenium 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。selenium 是一套完整的web应用程序测试系统,包含了测试的录制(selenium IDE),编写及运行(Selenium Remote Control)和测试的并行处理(Selenium Grid)。
Selenium的核心Selenium Core基于JsUnit,完全由JavaScript编写,因此可以用于任何支持JavaScript的浏览器上。
selenium可以模拟真实浏览器,自动化测试工具,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题
这里要说一下比较重要的PhantomJS,PhantomJS是一个而基于WebKit的服务端JavaScript API,支持Web而不需要浏览器支持,其快速、原生支持各种Web标准:Dom处理,CSS选择器,JSON等等。PhantomJS可以用用于页面自动化、网络监测、网页截屏,以及无界面测试。
由于新版本的selenium已经不支持PhantomJS,而Firefox和Chrome都带了无头模式,所以这里我们直接讲selenium的Firefox和Chrome的使用。

 

使用:

from selenium import webdriver#导入库

#声明浏览器
browser = webdriver.Chrome() #启动谷歌浏览器
#browser = webdriver.Firefox()#启动火狐浏览器 
url = 'https://www.baidu.com'
browser.get(url)#打开浏览器预设网址
print(browser.page_source)#打印网页源代码
browser.close()#关闭浏览器

元素查找:

id定位:find_element_by_id()
name定位:find_element_by_name()
class定位:find_element_by_class_name()
link定位:find_element_by_link_text()
partial link定位:find_element_by_partial_link_text()
tag定位:find_element_by_tag_name()
xpath定位:find_element_by_xpath()
css定位:find_element_by_css_selector()
from selenium import webdriver#导入库
browser = webdriver.Chrome()#声明浏览器
url = 'https:www.taobao.com'
browser.get(url)#打开浏览器预设网址
input_first = browser.find_element_by_id('q')
input_two = browser.find_element_by_css_selector('#q')
print(input_first)
print(input_two)

如果报错:

selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

原因是找不到可执行浏览器,或者版本不对,可到https://chromedriver.storage.googleapis.com/index.html
下载对应的版本,
复制到python库里面:

D:\Python27\Lib\site-packages\selenium\webdriver\chrome

或者配置环境变量

如果是火狐浏览器,可以到这里下载:

firefox:

http://releases.mozilla.org/pub/firefox/releases/

geckodriver

https://github.com/mozilla/geckodriver/releases

接下来,举例无头模式(无界面化)+爬虫实践案例:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

chrome_options = Options()
chrome_options.add_argument('--headless') #浏览器的无界面形态,即无头模式,如果不指定,则会在界面上弹窗浏览器窗口
chrome_options.add_argument('--disable-gpu')# 如果不加这个选项,有时定位会出现问题

chrome_driver=r"D:\Python27\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe"#指定要启动的浏览器,如果 配置了环境变量,可忽略
driver=webdriver.Chrome(executable_path=chrome_driver,chrome_options=chrome_options)
driver.get("https://www.jianshu.com/p/1531e12f8852")
time.sleep(3)
res = driver.find_elements_by_class_name('_1RuRku') #这里抓取到的数据,即使是js渲染的,也可以抓到,因为已经经过浏览器渲染
for r in res:
    print r.text
print res

driver.quit()

参考:
https://www.jianshu.com/p/1531e12f8852

转载请注明:永盟博客 » python+selenium库的基本使用

喜欢 (2)

Warning: count(): Parameter must be an array or an object that implements Countable in E:\www\blog\wp-includes\class-wp-comment-query.php on line 405