python中Selenium--》爬虫的终极大招,可用作自动化模拟操作

xiaoxiao2021-02-28  136

selenium是一个web的自动化测试工具,可以通过pip安装Python的selenium库来使用selenium

sudo pip install selenium

光有selenium是不够滴,还需要配合浏览器来使用,推荐使用一下浏览器,并配置好环境变量。

1.PhantomJS PhantomJS是一个无界面的浏览器,运行起来要比普通浏览器高效 需要安装PhantomJS 2.Chrome浏览器, 需要安装Chrome浏览器和对应版本的WebDriver 国内webdriver下载地址: http://npm.taobao.org/mirrors/chromedriver/

有了上面的步骤,就可以写代码了

等待页面加载完成的另类方法:

locator = (By.LINK_TEXT, '帮助') WebDriverWait(driver, 20, 0.5).until(expected_conditions.presence_of_element_located(locator))

整体代码

# coding=utf-8 # 第一个包 from selenium import webdriver # 第二个包 from selenium.webdriver.common.by import By # 第三个包 from selenium.webdriver.support.wait import WebDriverWait # 第四个包 from selenium.webdriver.support import expected_conditions # 第五个包 from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get('http://www.baidu.com') try: inp = driver.find_element_by_id('kw') su = driver.find_element_by_id('su') inp.send_keys('game of thrones') su.click() locator = (By.LINK_TEXT, '帮助') WebDriverWait(driver, 20, 0.5).until(expected_conditions.presence_of_element_located(locator)) inp = driver.find_element_by_id('kw') su = driver.find_element_by_id('su') inp.send_keys(Keys.CONTROL, 'a') inp.send_keys('Tencent') su.click() except Exception as e: print e
转载请注明原文地址: https://www.6miu.com/read-39660.html

最新回复(0)