selenium基礎-打開百度進行搜索


1. 安裝Python

2. 安裝selenium

3. 下載谷歌驅動ChromeDriver,放到Python的Scripts目錄下

4. 編寫代碼,如下

# coding: utf-8

from selenium import webdriver  # 瀏覽器驅動器
from selenium.webdriver.common.by import By  # 定位器
from selenium.webdriver.common.keys import Keys  # 鍵盤對象
from selenium.webdriver.support import expected_conditions as EC  # 判斷器
from selenium.webdriver.support.wait import WebDriverWait  # 瀏覽器等待對像
import time
# 創建一個谷歌瀏覽器對象
browser = webdriver.Chrome()

try:
    # 瀏覽器對象打開百度地址
    browser.get("https://www.baidu.com")
    # 查找id為 'kw'的標簽,即輸入框
    inputs = browser.find_element_by_id("kw")
    # 在輸入框中填入'Python'
    inputs.send_keys("Python")
    # '按下'回車鍵(第一種)
    inputs.send_keys(Keys.ENTER)
    # 點擊'百度一下'(第二種)
    # browser.find_element_by_id("su").click()
    # 創建一個等待對像,超時時間為10秒,調用的時間間隔為0.5
    wait = WebDriverWait(browser, 10, 0.5)
    # 每隔0.5秒檢查一次,直到頁面元素出現id為'content_left'的標簽
    wait.until(EC.presence_of_all_elements_located((By.ID, "content_left")))
except Exception as e:
    print e
else:
    # 打印請求的url
    print browser.current_url
    # 打印所有cookies
    print browser.get_cookies()
finally:
    # 等待10秒
    time.sleep(10)
    # 關閉瀏覽器對象
    browser.close()

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM