选择、操作web元素

11月1日

什么是web元素

Selenium自动化主要就是:选择界面元素,操作界面元素(输入操作:点击、输入文字、拖拽等,输出操作:获取元素的各种属性),根据界面上获取的数据进行分析和处理

选择元素

webdriver:操作整个浏览器和当前整个页面

  当前页面上的选择符合查找条件的对象

  打开网页,回退,前进,刷新网页

  获取、改变浏览器窗口的大小,关闭浏览器,截屏

  获取、设置cookies

WebElement:操作和对应web元素

  当前web元素的所有子元素里面符合查找条件的对象

  操作该web元素,比如:点击元素,输入字符,获取元素坐标、尺寸、文本内容、其它的属性信息

通过id选择元素

一个web元素

id是在DOM中唯一标志这个元素的属性:查找的效率最高

写法1:element = driver.find_element_by_id("kw")

写法2:

from selenium.webdirver.common.by import By

element = driver.find_element(by = By.ID,value = "kw")

没有找到

selenium.common.exception.NoSuchElementException

获取元素信息

text属性 显示该元素在web页面显示出来的文本内容

get_attribute 方法

某个属性的值 :ele.get_attribute('href')

该元素对应html源代码 :ele.get_attribute('outerHTML')

该元素的内部部分的html代码:ele.get_attribute('innerHTML')

BeautifulSpup4               官方文档https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

BS 是可以从HTML或XML文件中提取数据的库,Selenium 可以用来远程获取数据,有的时候感觉用selenium获取某些元素数据不太方便,可以将其父节点的html获取回来,利用BS在本地做分析

我们可以将它和Selenium 两种技术融合使用,达到我们的目的

安装

pip install beautifulsoup4 -i https://pypi.douban.com/simple/

pip install html5lib

soup =BeautifulSoup(html_doc, "html5lib")

print (soup.find('title')) <=> print (soup.title)     查找结尾为标签名为title的第一个元素

print (soup.find('title').name) <=> print (soup.title.name)  获取标签名

print (soup.find('title').string)  <=> print (soup.find('title').get_text())     获取标签名为title的文本

获取元素在尖括号里                         获取元素有子节点

print (soup.find_all('a')) 标签为a的所有元素的列表

通过name选择元素

一个web元素

<input name = "cheese" type = "text"/>

返回的是第一个找到的元素

cheese = driver.find_element_by_name("cheese")

或者

from selenium.webdirver.common.by import By

cheese = driver.find_element(By.NAME,"cheese")

返回所有元素

cheese = driver.find_elements_by_name("cheese")

或者

form selenium.webdriver.common.by import By

cheese = driver.find_elements(BY.NAME, "cheese")

如果找不到,返回空列表,不抛出异常

else = driver.find_elements_by_name('button3')

if eles:

  print('存在‘)

else:

  print(‘不存在’)

通过class选择元素,class比较多,通常查找的是列表

一个web元素

<div class= "cheese"><span>Cheddar</span></div>

<div class= "cheese"><span>Gouda</span></div>

返回所有元素

cheese = driver.find_elements_by_class_name("cheese")

或者

form selenium.webdirver.common.by import By

cheese = driver.find_elements(By.CLASS_NAME, "cheese")

通过tag名选择元素

tag名如果唯一的,可以通过tag名定位

假设html中有如下片段

<iframe src="..."></iframe>

可以

frame = driver.find_element_by_tag_name("iframe")

或者

from selenium.webdriver.common.by import By

frame = dirver.find_element(By.TAG_NAME,"iframe")

通过链接文本选择元素

对于链接,可以通过其链接文本的内容

<a href = "http://www.baidu.com">转到百度</a>

可以这样选择

ele = driver.find_element_by_link_text(u"转到百度"),python3 中不用加u

或者

from selenium.webdirver.common.by import By

ele = dirver.find_element(By.LINK_TEXT,u"转到百度“)

我们甚至只需要通过部分文本去找到该链接元素

ele = driver.find_element_by_partial_link_text(u"百度")

多钟技术实现目的

方法一

from selenium import webdriver

driver = webdriver.Chrome(r‘’)

driver.get('http://www.weather.com.cn/html/province/jiangsu.shtml')

ele = driver.find_element_by_id('forecastID')

# 写到这里,先运行一下,看看执行结果 
# 然后就是安装我们前面的一贯的思路,可以将
# 每个城市的信息存放到一个列表中
# 问大家怎么做?

cityWeathers = ele.text.split('℃ ')

#南京

#11℃/22

# 这样:citysWeather是每个城市的温度信息 list 
#
# 每个元素像这样: # 南京 # 12/27
#下面就是算法,算出温度最低城市,
# 有很多方法,大家看看这种
# 我们循环 去遍历这个城市文档信息列表,
# 得到城市名和 低气温的值,
#
# 依次和取出当前的所有城市最低气温比较,
# 如果更低,就记录到当前的低温城市列表中。

lowest = None # 记录目前最低温,先设置为None

lowestCities = [] # 温度最低城市列表

for one in cityWeahters:

  one = one.replace('','')

  cityname = one.split(' ')[0]

  lowTemp = int(one.split(' ')[1].split('/')[0])

  if lowest == None:

    lowest = lowTemp

    lowestCities.append()

  else lowTemp < lowest:

    lowest = lowTemp

    lowestCities = [cityname]

  elif lowTemp == lowest:

    lowestCities.append(cityname)

  print(f"最低温度为{lowest},城市有{','.join(lowestCities)}")

  driver.quit()

*************************************

from selenium import webdriver

driver = webdriver.Chrome(r‘’)

driver.get('http://www.weather.com.cn/html/province/jiangsu.shtml')

ele = driver.find_element_by_id('forecastID')

dls = ele.find_elements_by_tag_name('dl')

citys = []

for dl in dls:

  name = dl.find_element_by_tag_name('dt')

  ltemp = dl.find_element_by_tag_name('span').text

# 最高最低气温位置会变,根据位置决定是span还是b

  ltemp = int(ltemp.replace('','')

  citys.append([name,ltemp)

lowest = None

lowestCities = []

for one in citys:

  urcity = one[0]

  ltemp = one[1]

  curlowweather = ltemp

  if lowest == None or ltemp < lowest:

    lowest = ltemp

    lowestcitys = [curcity]

  elif ltemp == lowest:

    lowestCitys.append(curcity)

  print(f"最低温度为{lowest},城市有{','.join(lowestCities)}")

  driver.quit()

************************************************

from selenium import webdriver

driver = webdriver.Chrome(r‘’)

driver.get('http://www.weather.com.cn/html/province/jiangsu.shtml')

ele = driver.find_element_by_id('forecastID')

html_doc = ele.get_attribute('innerHTML')

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc, "html5lib")

dls = soup.find_all('d1')

citys = []

for dl in dls;

  name =dl.dt.a.string

  ltemp = dl.dd.span.string

  ltemp = int(ltemp.replace('℃',''))

  print(name, ltemp)

  citys.append([name,ltemp])

lowest = None

lowestCities = []

for one in citys:

  curcity = one[0]

  ltemp = one[1]

  curlowweather = ltemp

  if lowest == None or ltemp < lowest:

    lowest = ltemp

    lowestcitys = [curcity]

  elif ltemp == lowest:

    lowestCitys.append(curcity)

  print(f"最低温度为{lowest},城市有{','.join(lowestCities)}")

  driver.quit()

  

Selenium 作业 1

  1. 请到如下网址下载Chrome浏览器 的 web driver 驱动

https://chromedriver.storage.googleapis.com/2.33/chromedriver_win32.zip

  1. pip 安装Selenium Web driver Python 客户端库
练习1


1 访问如下网站,
http://121866.com/cust/sign.html

先注册一个账号, 记住用户名和密码。

2 然后开发一个自动化程序, 使用 用户名密码 自动化登录该网站,
并通过检查登录后右上角显示的用户名判断,是否登录成功。




练习2


1. 访问天气查询网站(网址如下),查询江苏省天气 
http://www.weather.com.cn/html/province/jiangsu.shtml

2. 获取江苏所有城市的天气,并找出其中每天最低气温最低的城市,显示出来,比如 
温度最低为12℃, 城市有连云港 盐城 

参考答案,往下翻

练习1

from selenium import webdriver
import time

driver = webdriver.Chrome(r"d:	oolswebdriverschromedriver.exe")

# ------------------------
driver.get('http://121866.com/cust/sign.html')

driver.find_element_by_id("username").send_keys('xxxx')
driver.find_element_by_id("password").send_keys('xxxx')

driver.find_element_by_id("btn_sign").click()
time.sleep(2)

expectStr = driver.find_element_by_id("username").text
if 'xxxx' ==  expectStr:
    print('测试通过')
else:
    print('测试不通过')

# ------------------------
input()
driver.quit()

练习2

from selenium import webdriver
driver = webdriver.Chrome(r"d:	oolswebdriverschromedriver.exe")

# ------------------------
driver.get('http://www.weather.com.cn/html/province/jiangsu.shtml')

ele = driver.find_element_by_id("forecastID")
print(ele.text)

''' 
citysWeather是每个城市的温度信息 list

每个元素像这样:
南京
12℃/27
'''
citysWeather = ele.text.split(u'℃
')


# 算出温度最低城市

lowest = 100
lowestCity = []  # 温度最低城市列表
for one in citysWeather:
    one = one.replace(u'℃','')
    print(one)
    curcity = one.split('
')[0]
    lowweather = one.split('/')[1]
    lowweather = int(lowweather)
    # 发现气温更低的城市
    if lowweather<lowest:
        lowest = lowweather
        lowestCity = [curcity]
    #  温度和当前最低相同,加入列表
    elif lowweather ==lowest:
        lowestCity.append(curcity)

print('温度最低为%s℃, 城市有%s' % (lowest, ' '.join(lowestCity)))

# ------------------------

driver.quit()
 
原文地址:https://www.cnblogs.com/hyzhang/p/7774006.html