Python知識(shí)分享網(wǎng) - 專業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
Python selenium交互
發(fā)布于:2023-10-29 21:11:25

2024 一天掌握python爬蟲【基礎(chǔ)篇】 涵蓋 requests、beautifulsoup、selenium

https://www.bilibili.com/video/BV1Ju4y1Y7k6/

 

selenium可以模擬用戶點(diǎn)擊事件,以及控制瀏覽器前進(jìn),后退等操作。

下面是一個(gè)模擬百度搜索,點(diǎn)擊下一頁(yè),控制瀏覽器后退,前進(jìn)的案例。

import time

from selenium import webdriver
from selenium.webdriver.common.by import By

# 創(chuàng)建瀏覽器操作對(duì)象
browser = webdriver.Chrome()

url = "https://www.baidu.com"

browser.get(url)

time.sleep(2)

# 獲取文本框的對(duì)象
input = browser.find_element(By.ID, "kw")

# 在文本框中輸入python
input.send_keys('python')

time.sleep(2)

# 獲取百度一下的按鈕
button = browser.find_element(By.ID, 'su')

# 點(diǎn)擊按鈕
button.click()

time.sleep(2)

# 滑到底部
# js_bottom = 'window.scrollTo(0,document.body.scrollHeight)'
js_bottom = 'document.documentElement.scrollTop=10000'
js_top = 'document.documentElement.scrollTop=0'
browser.execute_script(js_bottom)

time.sleep(2)

browser.execute_script(js_top)

time.sleep(2)

# 獲取下一頁(yè)的按鈕
next_button = browser.find_element(By.XPATH, '//a[@class="n"]')

# 點(diǎn)擊下一頁(yè)
next_button.click()

time.sleep(2)

browser.execute_script(js_bottom)

time.sleep(2)

# 返回到前一個(gè)歷史記錄 相當(dāng)于 瀏覽器的返回按鈕
browser.back()

time.sleep(2)

# 返回到后一個(gè)歷史記錄  相當(dāng)于 瀏覽器的前進(jìn)按鈕
browser.forward()

browser.execute_script(js_bottom)

time.sleep(2)

# 退出
browser.quit()

 

轉(zhuǎn)載自: