Python爬虫 selenium

2021-07-13 19:05

阅读:639

标签:httponly   res   url   end   tle   多个   ssi   phone   cell   

库的安装
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()
"""
"""

多个元素

第一种

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()

打印的结果如下

技术分享图片技术分享图片
print(lis)
browser.close()
["c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-1")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-2")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-3")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-4")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-5")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-6")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-7")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-8")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-9")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-10")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-11")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-12")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-13")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-14")>, "c26290835d4457ebf7d96bfab3740d19", element="0.09221044033125603-15")>, "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()

可了解更多可以查看: http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement

交互动作

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()

更多操作: http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains

执行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))
"""

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)

"""

NO LOGO

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)

打印结果:

"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)

打印结果:

"07dd2fbc2d5b1ce40e82b9754aba8fa8", element="0.5642646294074107-1")> "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

详细内容:http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.expected_conditions

前进与后退 

与浏览器的交互 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())

打印结果:

技术分享图片技术分享图片
[{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

详细文档:http://selenium-python.readthedocs.io/api.html#module-selenium.common.exceptions

 

Python爬虫 selenium

标签:httponly   res   url   end   tle   多个   ssi   phone   cell   

原文地址:https://www.cnblogs.com/tangkaishou/p/9541553.html


评论


亲,登录后才可以留言!