selenium的实际使用

发布于:2024-10-18 ⋅ 阅读:(66) ⋅ 点赞:(0)

1.标签页的切换

#获取当前所有的窗口

cur=driver.window_handles

#根据窗口索引进行切换

driver.switch_to.window(cur[1])

from selenium import webdriver

import time

driver = webdriver.Chrome()

driver.get('http://www.baidu.com')

time.sleep(1)

ele=driver.find_element_by_id('kw')

ele.send_keys('九歌‘)

time.sleep(2)





driver.find_element_by_id('su').click()

time.sleep(2)



#通过执行js来新开一个标签页

js='window.open("https://www.sougou.com")'

driver.execute_script(js)

time.sleep(1)

#获取所有的窗口

windows=driver.window_handles

#根据索引进行切换

driver.switch_to.window(window[0])

time.sleep(2)

driver.switch_to.window(window[1])

time.sleep(2)

driver.quit()

#2.页面滚动

driver = webdriver.Chrome()

driver.get('http://www.baidu.com')

time.sleep(1)

ele=driver.find_element_by_id('kw')

ele.send_keys('九歌‘)

time.sleep(1)

driver.find_element_by_id('su').click()



time.sleep(2)

//滚动到底部

#js='document.documentElement.scrollTop=8000'

//滚动部分

js='window.scrollTop(0,700)' # 700像素

driver.execute_script(js)

time.sleep(2)

driver.quit()

#3.京东图书

url=' '

#价格://*[@id="]_goodsLists"]/ul/li[*]/div/div[2]/strong/i

#标题://div[@class="p-name"]/a/em/text()

driver=webdriver.Chrome()

driver.get(url)

time.sleep(2)

data=driver.page_source

html=etree.HTML(data)
#标题

title=html.xpath('//div[@class="p-name"]/a/em/text()')

print(title)

#价格

price=html.xpath('//*[@id="]_goodsLists"]/ul/li[*]/div/div[2]/strong/i')

print(price)

driver.quit()

n=0

for t in title:

dic={}

dic['title']=t

dic['price']=price[n]

n+=1

print(dic)


今日签到

点亮在社区的每一天
去签到