iOS包大小計算
阿新 • • 發佈:2020-12-18
技術標籤:seleniumjavaxpathchromehtml
一、Xpath
注意:xpath中不能出現tbody標籤,可以用 //來跳過這個標籤
1、簡單使用物件例項化:
from lxml import etree
# 本地檔案:
tree = etree.parse('檔名')
tree.xpath('xpath表示式')
#網路資料:
tree = etree.HTML(網頁內容字串)
tree.xpath('xpath表示式')
2、常用的方法:
(1)屬性定位:
#找到class屬性值為song的div標籤 tree.xpath('//div[@class="song"]')
(2)層級&索引定位:
#找到class屬性值為tang的div的直系子標籤ul下的第二個子標籤li下的直系子標籤a
tree.xpath('//div[@class="tang"]/ul/li[2]/a')
(3)邏輯運算
#找到href屬性值為空且class屬性值為du的a標籤
tree.xpath(' //a[@href="" and @class="du"]’)
(4)模糊匹配
#找以class屬性值中有ng的div tree.xpath('//div[contains(@class, "ng")]') # 找以class屬性值為ta開頭的div tree.xpath(' //div[starts-with(@class, "ta")]')
(5)取文字
# /表示獲取當前標籤下的文字內容
//div[@class="song"]/p[1]/text()
# //表示獲取當前標籤下的文字內容和所有子標籤下的文字內容
//div[@class="tang"]//text()
(6)獲取屬性值
# 7 屬性獲取 @href 取當前標籤的屬性
etree.xpath('//body//a/@href')
(7)其他方法:
# # 注意從1 開始取(不是從0) a=html.xpath('//body//a[1]/@href') # 屬性多值匹配 # 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()') # 多屬性匹配 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()') # 按序選擇 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') # 節點軸選擇 # 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')
二、selenium
1、環境安裝
# 下載安裝selenium模組
pip install selenium
# 下載對應的瀏覽器版本驅動程式:chromdriver
國內映象網站地址:http://npm.taobao.org/mirrors/chromedriver/2.38/
2、簡單使用
from selenium import webdriver
import time
# bro=webdriver.Chrome() # 得到一個谷歌瀏覽器物件,
# 指定使用跟那個驅動
bro=webdriver.Chrome(executable_path='./chromedriver.exe') # 得到一個谷歌瀏覽器物件,
time.sleep(2)
bro.get('https://www.baidu.com/') # 在位址列裡輸入了百度
time.sleep(2)
# 獲取網頁內容
print(bro.page_source)
time.sleep(2)
# 關閉瀏覽器
bro.close()
3、標籤定位:find系列
'''
- id定位:find_element/elements_by_id()
- name定位:find_element_by_name()
- class定位:find_element_by_class_name()
- tag定位:find_element_by_tag_name()
- link(文字連結)定位:find_element_by_link_text()
- partial_link(模糊匹配)定位:find_element_by_partial_link_text()
- xpath定位:find_element_by_xpath()
- css定位:find_element_by_css-selector()
注意:element查詢的是第一符合條件的標籤
elements是查詢所有符合條件的標籤
'''
#===============示範用法===================
# 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()
4、標籤互動
'''
clear():清空輸入框內容
send_keys(keyword):輸入一個關鍵詞keyword
click():點選事件,強調事件的獨立
submit(): 用於對資訊的提交,提交物件是一個表單
'''
# =====例子=====
# 點選
button=browser.find_element_by_css_selector('#nav-search > form > div.nav-right > div > input')
button.click()
# 清空
input_tag=browser.find_element_by_id('twotabsearchtextbox')
input_tag.clear() #清空輸入框
# 輸入
input_tag.send_keys('iphone7plus')
5、獲取標籤屬性
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)
6、執行js程式
execute_script(js程式碼)
#例子:
bro.execute_script('window.scrollTo(0, document.body.scrollHeight)')
bro.execute_script('alert("123")')
7、其他方法:
'''
# 獲取頁面原始碼資料的方法
page_source
# 前進和後退的方法
forward() #前進
back() # 後退
# Cookie處理方法
get_cookies() # 獲取cookie
add_cooki() #新增cooki
delete_all_cookies() # 刪除cookies
'''
# ====案例====
# 模擬瀏覽器前進後退
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.page_source()
browser.forward()
# cookies的例子
browser=webdriver.Chrome()
browser.get('https://www.zhihu.com/explore')
# 獲取cookie值
print(browser.get_cookies())
# 新增cookies
browser.add_cookie({'k1':'xxx','k2':'yyy'})
print(browser.get_cookies())
# browser.delete_all_cookies()
8、無介面操作
####無介面瀏覽器(phantomjs)
#谷歌瀏覽器支援不開啟頁面
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
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下如果系統不支援視覺化不加這條會啟動失敗
#
bro=webdriver.Chrome(chrome_options=chrome_options,executable_path='./chromedriver.exe')
bro.get('https://www.baidu.com/')
# 視窗全屏
bro.maximize_window()
print(bro.page_source)
bro.close()
9、動作鏈
#1、匯入庫
from selenium.webdriver import ActionChains
# 例項化一個動作鏈物件:
action=AcitonChains(瀏覽器物件名字)
'''
方法:click_and_hold(div) #長按且點選操作
move_by_offset(x,y) # 移動
注意:要呼叫這個方法:perform(),否則該物件不會執行
如果定位的標籤存在iframe標籤,則必須使用switch_to.frame(id)
'''
# 例子:
#frame相當於一個單獨的網頁,在父frame裡是無法直接檢視到子frame的元素的,必須switch_to_frame切到該frame下,才能進一步查詢
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('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
```
browser.switch_to.frame('iframeResult') #切換到id為iframeResult的frame
```
tag1=browser.find_element_by_id('droppable')
print(tag1)
```
# tag2=browser.find_element_by_id('textareaCode') #報錯,在子frame裡無法檢視到父frame的元素
browser.switch_to.parent_frame() #切回父frame,就可以查詢到了
tag2=browser.find_element_by_id('textareaCode')
print(tag2)
```
finally:
browser.close()
10、顯隱式等待
#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')
#顯式等待:顯式地等待某個元素被載入
wait=WebDriverWait(browser,10)
wait.until(EC.presence_of_element_located((By.ID,'content_left')))
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()
模擬登陸案例
# -*-coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
import time
from chaojiying import Chaojiying_Client
from PIL import Image
chrome_options = Options()
chrome_options.add_argument('window-size=1920x3000')
bro = webdriver.Chrome(executable_path='./chromedriver.exe', chrome_options=chrome_options)
bro.get('https://www.12306.cn/index/')
time.sleep(1)
# 視窗最大化
bro.maximize_window()
time.sleep(2)
login_button = bro.find_element_by_xpath('//*[@id="J-header-login"]/a[1]')
login_button.click()
time.sleep(3)
#賬號密碼登陸
button = bro.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a')
button.click()
time.sleep(2)
bro.get_screenshot_as_file('web.png')
user_input = bro.find_element_by_id('J-userName')
user_input.send_keys('13927037099')
time.sleep(1)
passwd_input = bro.find_element_by_id('J-password')
passwd_input.send_keys('123456789')
code_tag = bro.find_element_by_id('J-loginImg')
# 驗證碼圖片大小
code_img_site = code_tag.size
# 驗證碼圖片位置
code_img_w = code_tag.location
x = int(code_img_w['x']) * 1.25
y = int(code_img_w['y']) * 1.25
height = int(code_img_site['height']) * 1.25
width = int(code_img_site['width']) * 1.25
# 因為我們桌面是125%顯示
img_tu = (x, y, x + width, y + height)
img = Image.open('./web.png')
code_img = img.crop(img_tu)
code_img.save('code_img.png')
#呼叫超級鷹識別驗證碼
chaojiying=Chaojiying_Client('賬號','密碼',' 應用id')
im=open('./code_img.png','rb').read()
result=chaojiying.PostPic(im,9004)
# 多個結果" 219,102 | 222,111
all_list=[]
if '|' in result['pic_str']:
pic_list=result['pic_str'].split('|')
for li in pic_list:
x_y_list=li.split(',')
l=[x_y_list[0],x_y_list[1]]
all_list.append(l)
else:
x_y_list=result['pic_str'].split(',')
l = [x_y_list[0], x_y_list[1]]
all_list.append(l)
#動作鏈
# 注意x,y要進行縮放,不然會發生點選偏移
for post in all_list:
x=int(post[0])/1.25
print(x)
y=int(post[1])/1.25
print(y)
ActionChains(bro).move_to_element_with_offset(code_tag,x,y).click().perform()
time.sleep(1)
bro.find_element_by_xpath('//*[@id="J-login"]').click()
bro.close()