python爬虫(selenium学习Ⅰ)

参考文章

打开谷歌浏览器

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys #键盘
import requests
b = webdriver.Chrome('D:\迅雷下载\chromecj.com\\chromedriver.exe')	#参数是谷歌驱动

进入某个网页,比如这里进入淘宝

url1 = 'http://www.taobao.com'
b.get(url1)

进入到某个网页,你就可以用一系列方法查询页面上的某个元素

b.find_element_by_id()	#根据id查询
b.find_element_by_xpath()	#根据xpath查询

, 鼠标悬停到某个元素上,并点击进入

three = b.find_element_by_xpath('/html/body/div[3]/div/ul[1]/li[1]/a')
ActionChains(b).move_to_element(three).perform()    #鼠标悬浮
three.click()

\color{Red}当然点击事件有两种写法

three = b.find_element_by_xpath('/html/body/div[3]/div/ul[1]/li[1]/a')
three.click()
#也可以写成three.send_keys(Keys.ENTER)

退 也可以实现浏览器的前进和后退

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys #键盘
import requests
import time

b = webdriver.Chrome('D:\迅雷下载\chromecj.com\\chromedriver.exe')

url = 'http://www.baidu.com'
url1 = 'http://www.taobao.com'
url2 = 'https://www.zhihu.com/'
b.get(url1)
time.sleep(2)
three = b.find_element_by_xpath('//*[@id="q"]')
three.send_keys('男士卫衣') #在输入框键入信息
three.clear()   #清除输入框
three.send_keys('女士卫衣')
three.send_keys(Keys.ENTER)

print(three.id)

#浏览器的前进和后退
b.get(url)
b.get(url1)
b.get(url2)
b.back()
time.sleep(1)
b.forward()
time.sleep(5)
b.close()

猜你喜欢

转载自blog.csdn.net/jziwjxjd/article/details/106912274