5.简单爬虫------------使用selenium

该文章仅供学习,如有错误,欢迎指出

这里列出了文档内的大部分可以使用的selenium代码
selenium中文文档地址:http://selenium-python-zh.readthedocs.io/en/latest/navigating.html#id2

assert()函数方法

格式: assert+空格+要判断语句,“报错语句”

assert "Python岁的三" in driver.title,'hahah'
#判断Python岁的三在不再title里面,如果不再则报错hahah
Traceback (most recent call last):
  File "/home/alpaca/hello/test.py", line 10, in <module>
    assert "Python岁的三" in driver.title,'hahah'
AssertionError: hahah

如果没有写'hahah'
则报错
Traceback (most recent call last):
  File "/home/alpaca/hello/test.py", line 10, in <module>
    assert "Python岁的三" in driver.title
AssertionError

1.声明驱动器

from selenium import webdriver
driver = webdriver.Firefox()

2.请求地址

driver.get("https://www.baidu.com/")

3.获取元素

element = driver.find_element_by_*()    根据什么什么内容查找元素

# element = driver.find_element_by_id()       根据id查找元素
# element = driver.find_element_by_name()   #根据name查找元素
element = driver.find_element_by_xpath()    #根据xpath查找
element = driver.find_element_by_css_selector() #根据css查找

4.获取键盘上的元素
http://selenium-python-zh.readthedocs.io/en/latest/locating-elements.html

#输入键盘上的内容
#from selenium.webdriver.common.keys import Keys
element.send_keys(Keys.ENTER)  #输入回车
element.send_keys(Keys.DOWN)    #输入下
element.send_keys('dsdsdsds') #输入dsdsdsds


.click()  模拟点击

5.清除元素,如清除输入框内的内容

element.clear()

6.退出编辑器

driver.close()                  #关闭所有标签
driver.quit()                    #关闭一个标签

7.selenium扩展————–远程调用selenium

2.5. 使用远程 Selenium WebDriver
为了使用远程 WebDriver, 你应该拥有一个正在运行的 Selenium 服务器。 通过下列命令运行服务器:

java -jar selenium-server-standalone-2.x.x.jar
Selenium 服务运行后, 你会看到这样的提示信息:

15:43:07.541 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
上面一行告诉你,你可以通过这个URL连接到远程WebDriver, 下面是一些例子:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.CHROME)

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.OPERA)

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities=DesiredCapabilities.HTMLUNITWITHJS)
`desired_capabilities`是一个字典,如果你不想使用默认的字典,你可以明确指定的值

driver = webdriver.Remote(
   command_executor='http://127.0.0.1:4444/wd/hub',
   desired_capabilities={'browserName': 'htmlunit',
                         'version': '2',
                        'javascriptEnabled': True})

8.使用select解决下拉框的问题

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_name('name'))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)


#取消所有选择

9.拖拽

from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()

猜你喜欢

转载自blog.csdn.net/llh_e/article/details/80623860