欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python爬虫 selenium

程序员文章站 2022-05-28 22:59:28
声明浏览器对象 访问页面 查找元素 查找单个元素的 element 查找多个元素的 elements 单个元素 第一种方式直接指定通过某种方式查找 find_element_by... 第二种方式 通过 find_element(By.xx , ' ....') 多个元素 第一种 打印的结果如下 p ......
库的安装
pip3 install selenium

声明浏览器对象

from selenium import webdriver

browser = webdriver.chrome()
browser = webdriver.firefox()
browser = webdriver.edge()
browser = webdriver.phantomjs()
browser = webdriver.safari()

访问页面

from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.taobao.com')
print(browser.page_source)
browser.close()

查找元素

查找单个元素的 element

* find_element_by_name
* find_element_by_xpath
* find_element_by_link_text
* find_element_by_partial_link_text
* find_element_by_tag_name
* find_element_by_class_name
* find_element_by_css_selector

查找多个元素的 elements

* find_elements_by_name
* find_elements_by_xpath
* find_elements_by_link_text
* find_elements_by_partial_link_text
* find_elements_by_tag_name
* find_elements_by_class_name
* find_elements_by_css_selector

单个元素

第一种方式直接指定通过某种方式查找 find_element_by...

from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element_by_id('q')
input_second = browser.find_element_by_css_selector('#q')
input_third = browser.find_element_by_xpath('//*[@id="q"]')
print(input_first, input_second, input_third)
browser.close()

第二种方式 通过 find_element(by.xx , ' ....')

from selenium import webdriver
from selenium.webdriver.common.by import by

browser = webdriver.chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element(by.id, 'q')
print(input_first)
browser.close()
"""
<selenium.webdriver.remote.webelement.webelement (session="1f209c0d11551c40d9d20ad964fef244", element="0.07914603542731591-1")>
"""

多个元素

第一种

from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.taobao.com')
lis = browser.find_elements_by_css_selector('.service-bd li')
print(lis)
browser.close()

打印的结果如下

Python爬虫 selenium
print(lis)
browser.close()
[<selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-1")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-2")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-3")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-4")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-5")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-6")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-7")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-8")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-9")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-10")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-11")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-12")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-13")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-14")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-15")>, <selenium.webdriver.remote.webelement.webelement (session="c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-16")>]
view code

第二种

from selenium import webdriver
from selenium.webdriver.common.by import by

browser = webdriver.chrome()
browser.get('https://www.taobao.com')
lis = browser.find_elements(by.css_selector, '.service-bd li')
print(lis)
browser.close()

元素交互操作

以下操作往淘宝输入框中输入 iphone 然后清空再输入 ipad 在点击搜索

from selenium import webdriver
import time

browser = webdriver.chrome()
browser.get('https://www.taobao.com')
input = browser.find_element_by_id('q')
input.send_keys('iphone')
time.sleep(1)
input.clear()
input.send_keys('ipad')
button = browser.find_element_by_class_name('btn-search')
button.click()

可了解更多可以查看: 

交互动作

from selenium import webdriver
from selenium.webdriver import actionchains

browser = webdriver.chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeresult') # 选择iframe
source = browser.find_element_by_css_selector('#draggable')
target = browser.find_element_by_css_selector('#droppable')
actions = actionchains(browser) # 动作链
actions.drag_and_drop(source, target)
actions.perform()

更多操作: 

执行javascript

通过函数 execute_script()

from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.zhihu.com/explore')
browser.execute_script('window.scrollto(0, document.body.scrollheight)')
browser.execute_script('alert("to bottom")')

获取元素信息

1.获取属性 get_attribute()

from selenium import webdriver
from selenium.webdriver import actionchains

browser = webdriver.chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo)
print(logo.get_attribute('class'))
"""
<selenium.webdriver.remote.webelement.webelement (session="e08c0f28d7f44d75ccd50df6bb676104", element="0.7236390660048155-1")>
zu-top-link-logo
"""

2.获取文本值 text

from selenium import webdriver

browser = webdriver.chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.text)

打印结果: 

提问

获取id、位置、标签名、大小等

from selenium import webdriver

browser = webdriver.chrome()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.id)
print(input.location)
print(input.tag_name)
print(input.size)

"""
0.6822924344980397-1
{'y': 7, 'x': 774}
button
{'height': 32, 'width': 66}
"""

frame 

切换 子iframe switch_to.frame("iframe的id值")

切换回来 switch_to.parent_frame()

import time
from selenium import webdriver
from selenium.common.exceptions import nosuchelementexception

browser = webdriver.chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeresult')
source = browser.find_element_by_css_selector('#draggable')
print(source)
try:
    logo = browser.find_element_by_class_name('logo')
except nosuchelementexception:
    print('no logo')
browser.switch_to.parent_frame()
logo = browser.find_element_by_class_name('logo')
print(logo)
print(logo.text)

"""
<selenium.webdriver.remote.webelement.webelement (session="4bb8ac03ced4ecbdefef03ffdc0e4ccd", element="0.44746093888932004-1")>
no logo
<selenium.webdriver.remote.webelement.webelement (session="4bb8ac03ced4ecbdefef03ffdc0e4ccd", element="0.13792611320464965-2")>
runoob.com
"""

等待

由于页面需要时间刷新,防止某些元素未刷新出来就访问导致出错,可设置等待时间

隐式等待

当使用了隐式等待执行测试的时候,如果 webdriver没有在 dom中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常, 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 dom,默认的时间是0

from selenium import webdriver

browser = webdriver.chrome()
browser.implicitly_wait(10) # 等待时间
browser.get('https://www.zhihu.com/explore')
input = browser.find_element_by_class_name('zu-top-add-question')
print(input)

打印结果:

<selenium.webdriver.remote.webelement.webelement (session="b29214772d59e912f1ac52e96ed29abe", element="0.12886805191194894-1")>

显示等待

from selenium import webdriver
from selenium.webdriver.common.by import by
from selenium.webdriver.support.ui import webdriverwait
from selenium.webdriver.support import expected_conditions as ec

browser = webdriver.chrome()
browser.get('https://www.taobao.com/')
wait = webdriverwait(browser, 10) # 最长的等待时间
input = wait.until(ec.presence_of_element_located((by.id, 'q')))
button = wait.until(ec.element_to_be_clickable((by.css_selector, '.btn-search')))
print(input, button)

打印结果:

<selenium.webdriver.remote.webelement.webelement (session="07dd2fbc2d5b1ce40e82b9754aba8fa8", element="0.5642646294074107-1")> <selenium.webdriver.remote.webelement.webelement (session="07dd2fbc2d5b1ce40e82b9754aba8fa8", element="0.5642646294074107-2")>

元素动作判断

title_is 标题是某内容
title_contains 标题包含某内容
presence_of_element_located 元素加载出,传入定位元组,如(by.id, 'p')
visibility_of_element_located 元素可见,传入定位元组
visibility_of 可见,传入元素对象
presence_of_all_elements_located 所有元素加载出
text_to_be_present_in_element 某个元素文本包含某文字
text_to_be_present_in_element_value 某个元素值包含某文字
frame_to_be_available_and_switch_to_it frame加载并切换
invisibility_of_element_located 元素不可见
element_to_be_clickable 元素可点击
staleness_of 判断一个元素是否仍在dom,可判断页面是否已经刷新
element_to_be_selected 元素可选择,传元素对象
element_located_to_be_selected 元素可选择,传入定位元组
element_selection_state_to_be 传入元素对象以及状态,相等返回true,否则返回false
element_located_selection_state_to_be 传入定位元组以及状态,相等返回true,否则返回false
alert_is_present 是否出现alert

详细内容:

前进与后退 

与浏览器的交互 back() 后退   froward() 前进

import time
from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.baidu.com/')
browser.get('https://www.taobao.com/')
browser.get('https://www.python.org/')
browser.back()
time.sleep(1)
browser.forward()
browser.close()

获取cookies 以及添加cookies

from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.zhihu.com/explore')
print(browser.get_cookies())
browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'germey'})
print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())

打印结果:

Python爬虫 selenium
[{'secure': false, 'value': '"ngm0ztm5ndawmweyndqwndk5odlkzwy3otkxy2i0ndy=|1491604091|236e34290a6f407bfbb517888849ea509ac366d0"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'l_cap_id', 'expiry': 1494196091.403418}, {'secure': false, 'value': '"yweyogy4mmi1mzq2ngy5mmfimjgzzguzzwjjytgwyjy=|1491604091|ff946847ddb5881245bdb7a5e6401b70dc61013f"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'cap_id', 'expiry': 1494196091.402855}, {'secure': false, 'value': '1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'l_n_c'}, {'secure': false, 'value': '"mjcxmde3yzu1yji4ndljzjljntq4zdiyowjjztbhnmy=|1491604091|8da4722b56a1545c2020dba97394a220c0eca8d9"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'r_cap_id', 'expiry': 1494196091.402525}, {'secure': false, 'value': '51854390', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmc'}, {'secure': false, 'value': '"aadco7e1kguptqveomieruzwka7zubhv-vy=|1491604091"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'd_c0', 'expiry': 1586212091.344773}, {'secure': false, 'value': '51854390.1491604091.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmz', 'expiry': 1507372091}, {'secure': false, 'value': '3cc99fc5-8706-43fc-90ac-3ad991bd1a25', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '_zap', 'expiry': 1554676091}, {'secure': false, 'value': '97cb00128ccb46659728f7c69cc191b0|1491604091000|1491604091000', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'q_c1', 'expiry': 1586212091.401644}, {'secure': false, 'value': '51854390.2.10.1491604091', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmb', 'expiry': 1491605891}, {'secure': false, 'value': '1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'n_c'}, {'secure': false, 'value': '51854390.000--|3=entry_date=20170408=1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmv', 'expiry': 1554676091}, {'secure': false, 'value': '51854390.669300758.1491604091.1491604091.1491604091.1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utma', 'expiry': 1554676091}, {'secure': false, 'value': '1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmt', 'expiry': 1491604691}, {'secure': false, 'value': 'aqaaalczuwh+dgiaeu3ppha+csdpnxvt', 'domain': 'www.zhihu.com', 'path': '/', 'httponly': true, 'name': 'aliyungf_tc'}]
[{'secure': false, 'value': 'germey', 'domain': '.www.zhihu.com', 'path': '/', 'httponly': false, 'name': 'name'}, {'secure': false, 'value': '"ngm0ztm5ndawmweyndqwndk5odlkzwy3otkxy2i0ndy=|1491604091|236e34290a6f407bfbb517888849ea509ac366d0"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'l_cap_id', 'expiry': 1494196091.403418}, {'secure': false, 'value': '"yweyogy4mmi1mzq2ngy5mmfimjgzzguzzwjjytgwyjy=|1491604091|ff946847ddb5881245bdb7a5e6401b70dc61013f"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'cap_id', 'expiry': 1494196091.402855}, {'secure': false, 'value': '1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'l_n_c'}, {'secure': false, 'value': '"mjcxmde3yzu1yji4ndljzjljntq4zdiyowjjztbhnmy=|1491604091|8da4722b56a1545c2020dba97394a220c0eca8d9"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'r_cap_id', 'expiry': 1494196091.402525}, {'secure': false, 'value': '51854390', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmc'}, {'secure': false, 'value': '"aadco7e1kguptqveomieruzwka7zubhv-vy=|1491604091"', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'd_c0', 'expiry': 1586212091.344773}, {'secure': false, 'value': '51854390.1491604091.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmz', 'expiry': 1507372091}, {'secure': false, 'value': '3cc99fc5-8706-43fc-90ac-3ad991bd1a25', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '_zap', 'expiry': 1554676091}, {'secure': false, 'value': '97cb00128ccb46659728f7c69cc191b0|1491604091000|1491604091000', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'q_c1', 'expiry': 1586212091.401644}, {'secure': false, 'value': '51854390.2.10.1491604091', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmb', 'expiry': 1491605891}, {'secure': false, 'value': '1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': 'n_c'}, {'secure': false, 'value': '51854390.000--|3=entry_date=20170408=1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmv', 'expiry': 1554676091}, {'secure': false, 'value': '51854390.669300758.1491604091.1491604091.1491604091.1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utma', 'expiry': 1554676091}, {'secure': false, 'value': '1', 'domain': '.zhihu.com', 'path': '/', 'httponly': false, 'name': '__utmt', 'expiry': 1491604691}, {'secure': false, 'value': 'aqaaalczuwh+dgiaeu3ppha+csdpnxvt', 'domain': 'www.zhihu.com', 'path': '/', 'httponly': true, 'name': 'aliyungf_tc'}]
[]
view code

浏览器选项卡的管理

通过switch_to_window(browser.window_handles[])

import time
from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.baidu.com')
browser.execute_script('window.open()')
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
browser.get('https://www.taobao.com')
time.sleep(1)
browser.switch_to_window(browser.window_handles[0])
browser.get('https://python.org')

打印结果:

['cdwindow-4f58e3a7-7167-4587-bedf-9cd8c867f435', 'cdwindow-6e05f076-6d77-453a-a36c-32baacc447df']

异常处理

比如下面的元素不存在的处理 打印肯定会报错的啦

from selenium import webdriver

browser = webdriver.chrome()
browser.get('https://www.baidu.com')
browser.find_element_by_id('hello')

处理方式:

from selenium import webdriver
from selenium.common.exceptions import timeoutexception, nosuchelementexception

browser = webdriver.chrome()
try:
    browser.get('https://www.baidu.com')
except timeoutexception:
    print('time out')
try:
    browser.find_element_by_id('hello')
except nosuchelementexception:
    print('no element')
finally:
    browser.close()

打印结果:

no element

详细文档: