一.百度識圖自動上傳圖片
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
edge_options = Options()
edge_options.binary_location = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
driver = webdriver.Edge(options=edge_options)
driver.get('https://graph.baidu.com/pcpage/index?tpl_from=pc')
driver.find_element(by=By.NAME, value='file').send_keys(r"D:\7.18\圖1.jpg")
input('')
代碼講解:百度識圖自動上傳圖片
這段代碼使用 Selenium 庫實現了自動打開百度識圖網頁并上傳本地圖片的功能。下面是對代碼的逐行解釋:
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
- 導入必要的 Selenium 模塊:
webdriver
用于控制瀏覽器,Options
用于配置瀏覽器選項,By
用于定位網頁元素。
?
edge_options = Options()
edge_options.binary_location = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
?
- 創建 Edge 瀏覽器的配置選項對象,并指定 Edge 瀏覽器的安裝路徑。這一步是可選的,如果 Edge 瀏覽器已添加到系統 PATH 中,可以省略。
driver = webdriver.Edge(options=edge_options)
- 初始化 Edge 瀏覽器驅動,創建一個可以控制瀏覽器的驅動對象。
driver.get('https://graph.baidu.com/pcpage/index?tpl_from=pc')
- 使用瀏覽器打開百度識圖的網頁。
?
driver.find_element(by=By.NAME, value='file').send_keys(r"D:\7.18\圖1.jpg")
?
- 定位網頁上的文件上傳元素(通過元素的
name
屬性值為file
來查找)。 - 使用
send_keys()
方法模擬鍵盤輸入,將本地圖片的路徑發送給上傳元素,從而實現自動上傳圖片。
input('')
不啟動瀏覽器獲取網頁資源
上述代碼使用了 Selenium WebDriver,它需要啟動一個真實的瀏覽器來執行操作。如果只需要獲取網頁的靜態資源(如 HTML 內容、JSON 數據等),可以使用更輕量級的庫,如requests
:
- 程序會在此處暫停,等待用戶輸入(按 Enter 鍵)后才會繼續執行并關閉瀏覽器。這通常用于調試時暫停程序,方便查看結果。
Selenium WebDriver 更多操作解釋
元素交互方法:
click()
:模擬鼠標點擊元素,常用于按鈕、鏈接等可點擊元素。send_keys(text)
:模擬鍵盤輸入文本到輸入框等元素中。clear()
:清空輸入框中的內容。submit()
:提交表單,通常用于表單中的提交按鈕。
瀏覽器導航方法:
back()
:模擬瀏覽器的后退按鈕,返回上一頁。forward()
:模擬瀏覽器的前進按鈕,前進到下一頁。refresh()
:刷新當前頁面。get(url)
:打開指定 URL 的網頁。current_url
:獲取當前頁面的 URL。
瀏覽器控制方法:
close()
:關閉當前瀏覽器窗口。quit()
:退出整個瀏覽器進程,關閉所有窗口。maximize_window()
:最大化瀏覽器窗口。set_window_size(width, height)
:設置瀏覽器窗口大小。
元素定位方法:
find_element(By.ID, value)
:通過元素 ID 定位。find_element(By.NAME, value)
:通過元素 name 屬性定位。find_element(By.CSS_SELECTOR, value)
:通過 CSS 選擇器定位。find_element(By.XPATH, value)
:通過 XPath 表達式定位。find_elements()
:返回所有匹配的元素列表。
import requestsurl = 'https://graph.baidu.com/pcpage/index?tpl_from=pc'
response = requests.get(url)if response.status_code == 200:# 獲取網頁的HTML內容html_content = response.textprint(html_content)
else:print(f"請求失敗,狀態碼:{response.status_code}")
二.批量獲取 Excel 相關圖書信息?
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
def get_info(driver):time.sleep(5)eles_p = driver.find_elements(By.CLASS_NAME, 'book_item')print(f"找到 {len(eles_p)} 個圖書項") # 調試輸出for ele_p in eles_p:ele_p.click()handles = driver.window_handlesdriver.switch_to.window(handles[-1])time.sleep(5)name = driver.find_element(By.CLASS_NAME, 'book-name').textprice = driver.find_element(By.CLASS_NAME, 'price').textauthor = driver.find_element(By.CLASS_NAME, 'book-author').textfile.write(f'圖書名:{name}\t價格:{price}\t作者名:{author}\n')print(f"已保存:{name}") # 調試輸出driver.close()driver.switch_to.window(handles[-2]) # 回到上一個標簽頁(索引-2)
file = open('excel圖書匯總.txt', 'w', encoding='utf-8')
chrome_options = Options()
chrome_options.binary_location = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
driver = webdriver.Edge(options=chrome_options)
driver.get('https://www.ptpress.com.cn/')
elements = driver.find_elements(By.TAG_NAME, "input")
elements[0].send_keys("excel" + Keys.RETURN)
handles = driver.window_handles
driver.switch_to.window(handles[1])
driver.find_element(By.ID, "booksMore").click()
handles = driver.window_handles
driver.switch_to.window(handles[-1])
get_info(driver)
page_num = 1 # 記錄當前頁碼
while True:try:# 嘗試查找下一頁按鈕next_button = driver.find_element(By.CLASS_NAME, 'ivu-page-next')# 檢查按鈕是否禁用(不同網站禁用狀態的class可能不同,需要根據實際情況調整)if 'ivu-page-disabled' in next_button.get_attribute('class'):print(f"已到達最后一頁(第{page_num}頁),停止爬取")breaknext_button.click()page_num += 1print(f"已翻到第{page_num}頁")time.sleep(3) # 等待頁面加載get_info(driver)except Exception as e:print(f"爬取過程中出錯:{e}")print(f"最后成功爬取的是第{page_num}頁")break
file.close()
driver.quit() # 關閉瀏覽器
代碼講解:批量獲取 Excel 相關圖書信息
這段代碼使用 Selenium 自動化瀏覽器操作,從人民郵電出版社網站批量獲取 Excel 相關圖書的信息,并保存到文本文件中。下面是對代碼的詳細解釋:
整體流程分析
這個程序主要分為以下幾個部分:
- 瀏覽器初始化與搜索
- 信息提取函數
- 翻頁與循環處理
- 異常處理與資源釋放
代碼詳細解釋
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
- 導入必要的庫:Selenium 相關模塊用于控制瀏覽器,time 模塊用于添加等待時間。
def get_info(driver):time.sleep(5)eles_p = driver.find_elements(By.CLASS_NAME, 'book_item')print(f"找到 {len(eles_p)} 個圖書項") # 調試輸出for ele_p in eles_p:ele_p.click()handles = driver.window_handlesdriver.switch_to.window(handles[-1])time.sleep(5)name = driver.find_element(By.CLASS_NAME, 'book-name').textprice = driver.find_element(By.CLASS_NAME, 'price').textauthor = driver.find_element(By.CLASS_NAME, 'book-author').textfile.write(f'圖書名:{name}\t價格:{price}\t作者名:{author}\n')print(f"已保存:{name}") # 調試輸出driver.close()driver.switch_to.window(handles[-2]) # 回到上一個標簽頁(索引-2)
- get_info 函數:負責從當前頁面提取圖書信息
- 等待 5 秒讓頁面加載完成
- 查找所有圖書項元素
- 遍歷每個圖書項,點擊打開詳情頁
- 切換到新打開的標簽頁
- 提取書名、價格和作者信息并寫入文件
- 關閉當前標簽頁,回到圖書列表頁
file = open('excel圖書匯總.txt', 'w', encoding='utf-8')
chrome_options = Options()
chrome_options.binary_location = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
driver = webdriver.Edge(options=chrome_options)
driver.get('https://www.ptpress.com.cn/')
- 打開文件用于保存數據
- 配置并啟動 Edge 瀏覽器
- 訪問人民郵電出版社網站
elements = driver.find_elements(By.TAG_NAME, "input")
elements[0].send_keys("excel" + Keys.RETURN)
handles = driver.window_handles
driver.switch_to.window(handles[1])
driver.find_element(By.ID, "booksMore").click()
handles = driver.window_handles
driver.switch_to.window(handles[-1])
get_info(driver)
- 找到搜索框并輸入 "excel" 進行搜索
- 切換到搜索結果頁面
- 點擊 "更多圖書" 按鈕
- 切換到新打開的圖書列表頁面
- 調用 get_info 函數提取第一頁的圖書信息
page_num = 1 # 記錄當前頁碼
while True:try:# 嘗試查找下一頁按鈕next_button = driver.find_element(By.CLASS_NAME, 'ivu-page-next')# 檢查按鈕是否禁用if 'ivu-page-disabled' in next_button.get_attribute('class'):print(f"已到達最后一頁(第{page_num}頁),停止爬取")breaknext_button.click()page_num += 1print(f"已翻到第{page_num}頁")time.sleep(3) # 等待頁面加載get_info(driver)except Exception as e:print(f"爬取過程中出錯:{e}")print(f"最后成功爬取的是第{page_num}頁")break
- 實現自動翻頁功能:
- 查找下一頁按鈕
- 檢查按鈕是否被禁用(表示已到最后一頁)
- 點擊下一頁按鈕并更新頁碼
- 等待頁面加載后繼續提取信息
- 使用 try-except 捕獲異常,確保程序健壯性
file.close()
driver.quit() # 關閉瀏覽器
- 關閉文件和瀏覽器,釋放資源
代碼優化建議
等待機制改進:
- 使用顯式等待替代固定的 time.sleep (),提高代碼穩定性
- 示例:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC# 等待圖書項元素加載完成
eles_p = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'book_item'))
)
異常處理增強:
- 在 get_info 函數中添加元素查找的異常處理
- 示例:
try:name = driver.find_element(By.CLASS_NAME, 'book-name').text
except:name = "未找到書名"
數據存儲優化:
- 考慮將數據保存為 CSV 或 Excel 格式,便于后續處理
- 示例:
import csvwith open('books.csv', 'w', newline='', encoding='utf-8') as csvfile:writer = csv.writer(csvfile)writer.writerow(['圖書名', '價格', '作者名'])writer.writerow([name, price, author])
增加日志記錄:
- 使用 logging 模塊替代簡單的 print 語句,便于調試和追蹤
- 示例:
import logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info(f"找到 {len(eles_p)} 個圖書項")
這個程序通過自動化瀏覽器操作,成功實現了批量獲取圖書信息的功能。通過合理的優化,可以進一步提高代碼的穩定性和可維護性。
?