selenium實戰腳本集(1)——新浪微博發送QQ每日焦點


背景

很多同學在工作中是沒有selenium的實戰環境的,因此自學的同學會感到有力無處使,想學習但又不知道怎么練習。其實學習新東西的道理都是想通的,那就是反復練習。這里乙醇會給出一些有用的,也富有挑戰的練習,幫助大家去快速掌握和使用selenium webdriver。多用才會有感觸。

練習

  • 首先去www.qq.com的首頁把今日話題的標題和url拿到
  • 然后去weibo.com登陸,登陸后發一條微博,內容就是今題話題的標題和url

用到的知識點

  • 自動登錄。微博登錄的時候有可能會有驗證碼,所以自動登錄什么的是極好的;這里建議用profile進行自動登錄;
  • 爬蟲知識。用webdriver去也頁面上爬一些內容。用到的核心api是getAttribute
  • css選擇器。微博的文本框用css選擇器去定位比較方便;

參考答案

#coding: utf-8
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from time import sleep

op = Options()
op.add_argument('user-data-dir=C:\Users\Administrator\AppData\Local\Google\Chrome\User Data')

dr = webdriver.Chrome(chrome_options=op)

dr.get('http://www.qq.com')
today_top_link = dr.find_element_by_css_selector('#todaytop a')
content = today_top_link.text
url = today_top_link.get_attribute('href')
print content
print url

dr.get('http://www.weibo.com')
sleep(2)

dr.find_element_by_css_selector('#v6_pl_content_publishertop .W_input').send_keys(content+url)
dr.find_element_by_css_selector('#v6_pl_content_publishertop .btn_30px').click()
sleep(2)
dr.close()

視頻詳解

常見錯誤

xp和win7下面chrome 的profile路徑是不一樣的

  • Windows XP:%USERPROFILE%\Local Settings\Application Data\Google\Chrome\User Data\
  • Windows Vista/Windows 7/Windows 8:%LOCALAPPDATA%\Google\Chrome\User Data\


免責聲明!

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



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