1. 程式人生 > 實用技巧 >字串的常用方法

字串的常用方法

目錄

介紹

selenium最初是一個自動化測試工具,而爬蟲中使用它主要是為了解決requests無法直接執行JavaScript程式碼的問題

selenium本質是通過驅動瀏覽器,完全模擬瀏覽器的操作,比如跳轉、輸入、點選、下拉等,來拿到網頁渲染之後的結果,可支援多種瀏覽器

from selenium import webdriver
browser=webdriver.Chrome()
browser=webdriver.Firefox()
browser=webdriver.PhantomJS()
browser=webdriver.Safari()
browser=webdriver.Edge()

官網:http://selenium-python.readthedocs.io

安裝使用

有介面瀏覽器

#安裝:selenium+chromedriver
pip3 install selenium
下載chromdriver.exe放到python安裝路徑的scripts目錄中即可,注意最新版本是2.38,並非2.9
國內映象網站地址:http://npm.taobao.org/mirrors/chromedriver/2.38/
最新的版本去官網找:https://sites.google.com/a/chromium.org/chromedriver/downloads

#驗證安裝
C:\Users\Administrator>python3
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from selenium import webdriver
>>> driver=webdriver.Chrome() #彈出瀏覽器
>>> driver.get('https://www.baidu.com')
>>> driver.page_source # 當前頁面所有內容

#注意:
selenium3預設支援的webdriver是Firfox,而Firefox需要安裝geckodriver
下載連結:https://github.com/mozilla/geckodriver/releases

無介面瀏覽器

#selenium:3.12.0
#webdriver:2.38
#chrome.exe: 65.0.3325.181(正式版本) (32 位)

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('window-size=1920x3000') #指定瀏覽器解析度
chrome_options.add_argument('--disable-gpu') #谷歌文件提到需要加上這個屬性來規避bug
chrome_options.add_argument('--hide-scrollbars') #隱藏滾動條, 應對一些特殊頁面
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不載入圖片, 提升速度

chrome_options.add_argument('--headless') #瀏覽器不提供視覺化頁面. linux下如果系統不支援視覺化不加這條會啟動失敗

chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" #手動指定使用的瀏覽器位置


driver=webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://www.baidu.com')

print('hao123' in driver.page_source)


driver.close() #切記關閉瀏覽器,回收資源

基本使用

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #鍵盤按鍵操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待頁面載入某些元素

browser=webdriver.Chrome()
try:
    browser.get('https://www.baidu.com')

    input_tag=browser.find_element_by_id('kw')
    input_tag.send_keys('美女') #python2中輸入中文錯誤,字串前加個u
    input_tag.send_keys(Keys.ENTER) #輸入回車

    wait=WebDriverWait(browser,10)
    wait.until(EC.presence_of_element_located((By.ID,'content_left'))) #等到id為content_left的元素載入完畢,最多等10秒

    print(browser.page_source)
    print(browser.current_url)
    print(browser.get_cookies())

finally:
    browser.close()

選擇器

基本用法

#官網連結:http://selenium-python.readthedocs.io/locating-elements.html
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
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

driver=webdriver.Chrome()
driver.get('https://www.baidu.com')
wait=WebDriverWait(driver,10)

try:
    #===============所有方法===================
    # 1、find_element_by_id
    # 2、find_element_by_link_text
    # 3、find_element_by_partial_link_text
    # 4、find_element_by_tag_name
    # 5、find_element_by_class_name
    # 6、find_element_by_name
    # 7、find_element_by_css_selector
    # 8、find_element_by_xpath
    # 強調:
    # 1、上述均可以改寫成find_element(By.ID,'kw')的形式
    # 2、find_elements_by_xxx的形式是查詢到多個元素,結果為列表

    #===============示範用法===================
    # 1、find_element_by_id
    print(driver.find_element_by_id('kw'))

    # 2、find_element_by_link_text
    login=driver.find_element_by_link_text('登入')
    login.click()

    # 3、find_element_by_partial_link_text
    login=driver.find_elements_by_partial_link_text('錄')[0]
    login.click()

    # 4、find_element_by_tag_name
    print(driver.find_element_by_tag_name('a'))

    # 5、find_element_by_class_name
    button=wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'tang-pass-footerBarULogin')))
    button.click()

    # 6、find_element_by_name
    input_user=wait.until(EC.presence_of_element_located((By.NAME,'userName')))
    input_pwd=wait.until(EC.presence_of_element_located((By.NAME,'password')))
    commit=wait.until(EC.element_to_be_clickable((By.ID,'TANGRAM__PSP_10__submit')))

    input_user.send_keys('18611453110')
    input_pwd.send_keys('xxxxxx')
    commit.click()

    # 7、find_element_by_css_selector
    driver.find_element_by_css_selector('#kw')

    # 8、find_element_by_xpath

    time.sleep(5)

finally:
    driver.close()

xpath




#官網連結:http://selenium-python.readthedocs.io/locating-elements.html
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
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

driver=webdriver.PhantomJS()
driver.get('https://doc.scrapy.org/en/latest/_static/selectors-sample1.html')
# wait=WebDriverWait(driver,3)
driver.implicitly_wait(3) #使用隱式等待

try:
    # find_element_by_xpath
    #//與/
    # driver.find_element_by_xpath('//body/a')  # 開頭的//代表從整篇文件中尋找,body之後的/代表body的兒子,這一行找不到就會報錯了

    driver.find_element_by_xpath('//body//a')  # 開頭的//代表從整篇文件中尋找,body之後的//代表body的子子孫孫
    driver.find_element_by_css_selector('body a')

    #取第n個
    res1=driver.find_elements_by_xpath('//body//a[1]') #取第一個a標籤
    print(res1[0].text)

    #按照屬性查詢,下述三者查詢效果一樣
    res1=driver.find_element_by_xpath('//a[5]')
    res2=driver.find_element_by_xpath('//a[@href="image5.html"]')
    res3=driver.find_element_by_xpath('//a[contains(@href,"image5")]') #模糊查詢
    print('==>', res1.text)
    print('==>',res2.text)
    print('==>',res3.text)


    #其他
    res1=driver.find_element_by_xpath('/html/body/div/a')
    print(res1.text)

    res2=driver.find_element_by_xpath('//a[img/@src="image3_thumb.jpg"]') #找到子標籤img的src屬性為image3_thumb.jpg的a標籤
    print(res2.tag_name,res2.text)

    res3 = driver.find_element_by_xpath("//input[@name='continue'][@type='button']") #檢視屬性name為continue且屬性type為button的input標籤
    res4 = driver.find_element_by_xpath("//*[@name='continue'][@type='button']") #檢視屬性name為continue且屬性type為button的所有標籤
    
    
    time.sleep(5)

finally:
    driver.close()
# xpath: XPath 是一門在 XML 文件中查詢資訊的語言
# / :從根節點選取。
# // :不管位置,直接找
# /@屬性名
# /text() 取文字

doc='''
<html>
 <head>
  <base href='http://example.com/' />
  <title>Example website</title>
 </head>
 <body>
  <div id='images'>
   <a href='image1.html' aa='bb'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
   <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
   <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
   <a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
   <a href='image5.html' class='li li-item' name='items'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
   <a href='image6.html' name='items'><span><h5>test</h5></span>Name: My image 6 <br /><img src='image6_thumb.jpg' /></a>
  </div>
 </body>
</html>
'''
from lxml import etree

html=etree.HTML(doc)
# html=etree.parse('search.html',etree.HTMLParser())

#1 所有節點
a=html.xpath('//*')

#2 指定節點(結果為列表)
a=html.xpath('//head')

#3 子節點,子孫節點
a=html.xpath('//div/a')
a=html.xpath('//body/a') #無資料
a=html.xpath('//body//a')


#4 父節點
a=html.xpath('//body//a[@href="image1.html"]/..')
a=html.xpath('//body//a[1]/..')
也可以這樣
a=html.xpath('//body//a[1]/parent::*')


#5 屬性匹配
a=html.xpath('//body//a[@href="image1.html"]')

#6 文字獲取(重要)  /text() 取當前標籤的文字
a=html.xpath('//body//a[@href="image1.html"]/text()')
a=html.xpath('//body//a/text()')

#7 屬性獲取  @href 取當前標籤的屬性
a=html.xpath('//body//a/@href')

# 注意從1 開始取(不是從0)
a=html.xpath('//body//a[1]/@href')

#8 屬性多值匹配
#a 標籤有多個class類,直接匹配就不可以了,需要用contains
a=html.xpath('//body//a[@class="li"]')
a=html.xpath('//body//a[contains(@class,"li")]')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

#9 多屬性匹配
a=html.xpath('//body//a[contains(@class,"li") or @name="items"]')
a=html.xpath('//body//a[contains(@class,"li") and @name="items"]/text()')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

#10 按序選擇
a=html.xpath('//a[2]/text()')
a=html.xpath('//a[2]/@href')
取最後一個
a=html.xpath('//a[last()]/@href')
位置小於3的
a=html.xpath('//a[position()<3]/@href')
倒數第二個
a=html.xpath('//a[last()-2]/@href')

# 11 節點軸選擇
ancestor:祖先節點
使用了* 獲取所有祖先節點
a=html.xpath('//a/ancestor::*')
# 獲取祖先節點中的div
a=html.xpath('//a/ancestor::div')
attribute:屬性值
a=html.xpath('//a[1]/attribute::*')
a=html.xpath('//a[1]/@aa')
child:直接子節點
a=html.xpath('//a[1]/child::*')
a=html.xpath('//a[1]/child::img/@src')
descendant:所有子孫節點
a=html.xpath('//a[6]/descendant::*')
a=html.xpath('//a[6]/descendant::h5/text()')
following:當前節點之後所有節點(兄弟節點和兄弟內部的節點)
a=html.xpath('//a[1]/following::*')
a=html.xpath('//a[1]/following::*[1]/@href')
following-sibling:當前節點之後同級節點(只找兄弟)
a=html.xpath('//a[1]/following-sibling::*')
a=html.xpath('//a[1]/following-sibling::a')
a=html.xpath('//a[1]/following-sibling::*[2]')
a=html.xpath('//a[1]/following-sibling::*[2]/@href')

獲取標籤屬性

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #鍵盤按鍵操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待頁面載入某些元素

browser=webdriver.Chrome()

browser.get('https://www.amazon.cn/')

wait=WebDriverWait(browser,10)
wait.until(EC.presence_of_element_located((By.ID,'cc-lm-tcgShowImgContainer')))

tag=browser.find_element(By.CSS_SELECTOR,'#cc-lm-tcgShowImgContainer img')

#獲取標籤屬性,
print(tag.get_attribute('src'))


#獲取標籤ID,位置,名稱,大小(瞭解)
print(tag.id)
print(tag.location)
print(tag.tag_name)
print(tag.size)


browser.close()

獲取標籤屬性

等待元素被載入

#1、selenium只是模擬瀏覽器的行為,而瀏覽器解析頁面是需要時間的(執行css,js),一些元素可能需要過一段時間才能加載出來,為了保證能查詢到元素,必須等待

#2、等待的方式分兩種:
隱式等待:在browser.get('xxx')前就設定,針對所有元素有效
顯式等待:在browser.get('xxx')之後設定,只針對某個元素有效

隱式等待

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #鍵盤按鍵操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待頁面載入某些元素

browser=webdriver.Chrome()

#隱式等待:在查詢所有元素時,如果尚未被載入,則等10秒
browser.implicitly_wait(10)

browser.get('https://www.baidu.com')


input_tag=browser.find_element_by_id('kw')
input_tag.send_keys('美女')
input_tag.send_keys(Keys.ENTER)

contents=browser.find_element_by_id('content_left') #沒有等待環節而直接查詢,找不到則會報錯
print(contents)

browser.close()

顯式等待

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #鍵盤按鍵操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待頁面載入某些元素

browser=webdriver.Chrome()
browser.get('https://www.baidu.com')


input_tag=browser.find_element_by_id('kw')
input_tag.send_keys('美女')
input_tag.send_keys(Keys.ENTER)


#顯式等待:顯式地等待某個元素被載入
wait=WebDriverWait(browser,10)
wait.until(EC.presence_of_element_located((By.ID,'content_left')))

contents=browser.find_element(By.CSS_SELECTOR,'#content_left')
print(contents)


browser.close()

元素互動操作

'''點選,清空'''
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #鍵盤按鍵操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待頁面載入某些元素

browser=webdriver.Chrome()
browser.get('https://www.amazon.cn/')
wait=WebDriverWait(browser,10)


input_tag=wait.until(EC.presence_of_element_located((By.ID,'twotabsearchtextbox')))
input_tag.send_keys('iphone 8')
button=browser.find_element_by_css_selector('#nav-search > form > div.nav-right > div > input')
button.click()


import time
time.sleep(3)

input_tag=browser.find_element_by_id('twotabsearchtextbox')
input_tag.clear() #清空輸入框
input_tag.send_keys('iphone7plus')
button=browser.find_element_by_css_selector('#nav-search > form > div.nav-right > div > input')
button.click()
browser.close()



'''Action Chains'''
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By  # 按照什麼方式查詢,By.ID,By.CSS_SELECTOR
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

driver = webdriver.Chrome()
driver.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
wait=WebDriverWait(driver,3)
# driver.implicitly_wait(3)  # 使用隱式等待

try:
    driver.switch_to.frame('iframeResult') ##切換到iframeResult
    sourse=driver.find_element_by_id('draggable')
    target=driver.find_element_by_id('droppable')

    #方式一:基於同一個動作鏈序列執行
    # actions=ActionChains(driver) #拿到動作鏈物件
    # actions.drag_and_drop(sourse,target) #把動作放到動作鏈中,準備序列執行
    # actions.perform()

    #方式二:不同的動作鏈,每次移動的位移都不同
    ActionChains(driver).click_and_hold(sourse).perform()
    distance=target.location['x']-sourse.location['x']

    track=0
    while track < distance:
        ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform()
        track+=2

    ActionChains(driver).release().perform()

    time.sleep(10)

finally:
    driver.close()




'''在互動動作比較難實現的時候可以自己寫JS'''
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #鍵盤按鍵操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待頁面載入某些元素


try:
    browser=webdriver.Chrome()
    browser.get('https://www.baidu.com')
    browser.execute_script('alert("hello world")') #列印警告
    # window.scrollTo(0, document.body.offsetHeight) 頁面滑到底部
finally:
    browser.close()

其他

模擬瀏覽器的前進後退

import time
from selenium import webdriver

browser=webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.get('https://www.taobao.com')
browser.get('http://www.sina.com.cn/')

browser.back()
time.sleep(10)
browser.forward()
browser.close()

cookies

from selenium import webdriver

browser=webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
print(browser.get_cookies())
browser.add_cookie({'k1':'xxx','k2':'yyy'})
print(browser.get_cookies())

# browser.delete_all_cookies()

選項卡管理

#選項卡管理:切換選項卡,有js的方式windows.open,有windows快捷鍵:ctrl+t等,最通用的就是js的方式
import time
from selenium import webdriver

browser=webdriver.Chrome()
browser.get('https://www.baidu.com')
browser.execute_script('window.open()')

print(browser.window_handles) #獲取所有的選項卡
browser.switch_to_window(browser.window_handles[1])
browser.get('https://www.taobao.com')
time.sleep(10)
browser.switch_to_window(browser.window_handles[0])
browser.get('https://www.sina.com.cn')
browser.close()

異常處理

from selenium import webdriver
from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException

try:
    browser=webdriver.Chrome()
    browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
    browser.switch_to.frame('iframssseResult')

except TimeoutException as e:
    print(e)
except NoSuchFrameException as e:
    print(e)
finally:
    browser.close()

練習

自動登入163郵箱併發送郵件

#注意:網站都策略都是在不斷變化的,精髓在於學習流程。下述程式碼生效與2017-11-7,不能保證永久有效
from selenium import webdriver
from selenium.webdriver import ActionChains
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

browser=webdriver.Chrome()

try:
    browser.get('http://mail.163.com/')

    wait=WebDriverWait(browser,5)

    frame=wait.until(EC.presence_of_element_located((By.ID,'x-URS-iframe')))
    browser.switch_to.frame(frame)

    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.m-container')))

    inp_user=browser.find_element_by_name('email')
    inp_pwd=browser.find_element_by_name('password')
    button=browser.find_element_by_id('dologin')
    inp_user.send_keys('18611453110')
    inp_pwd.send_keys('xxxx')
    button.click()

    #如果遇到驗證碼,可以把下面一小段開啟註釋
    # import time
    # time.sleep(10)
    # button = browser.find_element_by_id('dologin')
    # button.click()

    wait.until(EC.presence_of_element_located((By.ID,'dvNavTop')))
    write_msg=browser.find_elements_by_css_selector('#dvNavTop li')[1] #獲取第二個li標籤就是“寫信”了
    write_msg.click()


    wait.until(EC.presence_of_element_located((By.CLASS_NAME,'tH0')))
    recv_man=browser.find_element_by_class_name('nui-editableAddr-ipt')
    title=browser.find_element_by_css_selector('.dG0 .nui-ipt-input')
    recv_man.send_keys('[email protected]')
    title.send_keys('聖旨')
    print(title.tag_name)


    frame=wait.until(EC.presence_of_element_located((By.CLASS_NAME,'APP-editor-iframe')))
    browser.switch_to.frame(frame)
    body=browser.find_element(By.CSS_SELECTOR,'body')
    body.send_keys('egon很帥,可以加工資了')

    browser.switch_to.parent_frame() #切回他爹
    send_button=browser.find_element_by_class_name('nui-toolbar-item')
    send_button.click()

    #可以睡時間久一點別讓瀏覽器關掉,看看傳送成功沒有
    import time
    time.sleep(10000)

except Exception as e:
    print(e)
finally:
    browser.close()

爬取京東商城商品資訊

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什麼方式查詢,By.ID,By.CSS_SELECTOR
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


def get_goods(driver):
    try:
        goods=driver.find_elements_by_class_name('gl-item')

        for good in goods:
            detail_url=good.find_element_by_tag_name('a').get_attribute('href')

            p_name=good.find_element_by_css_selector('.p-name em').text.replace('\n','')
            price=good.find_element_by_css_selector('.p-price i').text
            p_commit=good.find_element_by_css_selector('.p-commit a').text

            msg = '''
            商品 : %s
            連結 : %s
            價錢 :%s
            評論 :%s
            ''' % (p_name,detail_url,price,p_commit)

            print(msg,end='\n\n')


        button=driver.find_element_by_partial_link_text('下一頁')
        button.click()
        time.sleep(1)
        get_goods(driver)
    except Exception:
        pass

def spider(url,keyword):
    driver = webdriver.Chrome()
    driver.get(url)
    driver.implicitly_wait(3)  # 使用隱式等待
    try:
        input_tag=driver.find_element_by_id('key')
        input_tag.send_keys(keyword)
        input_tag.send_keys(Keys.ENTER)
        get_goods(driver)
    finally:
        driver.close()


if __name__ == '__main__':
    spider('https://www.jd.com/',keyword='iPhone8手機')