day05 selenium
生活随笔
收集整理的這篇文章主要介紹了
day05 selenium
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
from selenium import webdriver
# 導入鍵盤Keys
from selenium.webdriver.common.keys import Keys
import timedriver = webdriver.Chrome()# 檢測代碼塊
try:# 隱式等待,等待標簽加載driver.implicitly_wait(10)# 往京東主頁發送請求driver.get('https://www.jd.com/')# 通過id查找input輸入框input_tag = driver.find_element_by_id('key')# send_keys為當前標簽傳值input_tag.send_keys('中華字典')# 按鍵盤的回車鍵
input_tag.send_keys(Keys.ENTER)time.sleep(3)'''爬取京東商品信息:公仔名稱url價格評價'''# element 找一個# elements 找多個# 查找所有的商品列表good_list = driver.find_elements_by_class_name('gl-item')# print(good_list)# 循環遍歷每一個商品for good in good_list:# 通過屬性選擇器查找商品詳情頁url# urlgood_url = good.find_element_by_css_selector('.p-img a').get_attribute('href')print(good_url)# 名稱good_name = good.find_element_by_css_selector('.p-name em').textprint(good_name)# 價格good_price = good.find_element_by_class_name('p-price').textprint(good_price)# 評價數good_commit = good.find_element_by_class_name('p-commit').textprint(good_commit)str1 = f'''url: {good_url}名稱: {good_name}價格: {good_price}評價: {good_commit}\n'''# 把商品信息寫入文本中with open('jd.txt', 'a', encoding='utf-8') as f:f.write(str1)time.sleep(10)# 捕獲異常
except Exception as e:print(e)# 最后都會把驅動瀏覽器關閉掉
finally:driver.close()
運行結果:
?
轉載于:https://www.cnblogs.com/cangbao/p/11104512.html
總結
以上是生活随笔為你收集整理的day05 selenium的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: step1 . day2:Linux系统
- 下一篇: 创建 linuxrc 文件