首先,需要用到python的一个库selenium,安装方法也很简单,使用pip安装。
pip install selenium
pip3 install selenium
selenium脚本可以控制常见的浏览器,需要先安装浏览器驱动。 推荐使用Chrome浏览器: Chrome浏览器插件下载
  找到对应版本的插件,如果是最新版本浏览器没找到对应版本也可以下载最后一个版本的插件。 将下载好的chromedriver_win32.zip解压后是一个exe文件,将其复制到你的Python安装根目录下就好了。
示例代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import datetime
browser = webdriver.Chrome()
try:
print(datetime.datetime.now())
browser.get('https://www.baidu.com')
time.sleep(1)
input = browser.find_element(By.ID, 'kw')
input.send_keys('慕课网')
input.send_keys(Keys.ENTER)
print('current_url:')
print(browser.current_url)
time.sleep(1)
goChooseShiftBt = browser.find_element(By.XPATH, "//*[contains(text(),'程序员的梦工厂')]")
goChooseShiftBt.click()
time.sleep(1)
wins = browser.window_handles
print("当前所有的窗口句柄:", wins)
browser.switch_to.window(wins[-1])
time.sleep(1)
input2 = browser.find_element(By.CLASS_NAME, "search-input")
input2.send_keys('python')
input2.send_keys(Keys.ENTER)
time.sleep(1)
print('current_url:')
print(browser.current_url)
print('------------------------------------------------------------------')
print(browser.get_cookies())
print('------------------------------------------------------------------')
print(browser.page_source)
except Exception as e:
print('str Error:')
print(str(e))
error_msg = repr(e)
print('repr Error:')
if 'NoSuchElementException' in error_msg :
print('没找到元素')
else:
print(repr(e))
finally:
time.sleep(2)
print('---------关闭浏览器---------')
browser.close()
browser.quit()
print(datetime.datetime.now())
pycharm可以直接用电脑管家这版免费的:  
|