目录
前言
学习 Selenium自动化测试框架,在Anaconda的一个虚拟环境下安装selenium 和webdrive等必要库。熟练掌握在浏览器的开发者模式(Chrome 和Edge 浏览器按F12 )下对网页结构进行分析,找到对应网页元素的技能。然后完成下列任务:
1)对一个网页进行自动化测试。比如自动填充百度网页的查询关键字,完成自动搜索。
2)爬取一个动态网页的数据,按附件要求实现代码。
3)爬取京东网站上的感兴趣书籍信息(如关键字“python编程”的前200本图书),并保存。
一.Selenium
1.简介
Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开发的,类型像我们玩游戏用的按键精灵,可以按指定的命令自动操作,不同是Selenium 可以直接运行在浏览器上,它支持所有主流的浏览器(包括PhantomJS这些无界面的浏览器)。
Selenium 可以根据我们的指令,让浏览器自动加载页面,获取需要的数据,甚至页面截屏,或者判断网站上某些动作是否发生。
Selenium 自己不带浏览器,不支持浏览器的功能,它需要与第三方浏览器结合在一起才能使用。但是我们有时候需要让它内嵌在代码中运行,所以我们可以用一个叫 PhantomJS 的工具代替真实的浏览器。
2.环境配置
打开Anaconda Prompt
conda install selenium
3.安装驱动
selenium官网驱动下载(Downloads | Selenium)
Chrome的 ChromeDriver Mirror
二.爬取一个动态网页的数据
代码
def write_csv(csv_head,csv_content,csv_path):
with open(csv_path, 'w', newline='',encoding='utf-8') as file:
fileWriter =csv.writer(file)
fileWriter.writerow(csv_head)
fileWriter.writerows(csv_content)
print('爬取信息成功')
quote=driver.find_elements_by_class_name("quote")
#将要收集的信息放在quote_content里
for i in tqdm(range(len(quote))):
quote_text=quote[i].find_element_by_class_name("text")
quote_author=quote[i].find_element_by_class_name("author")
temp=[]
temp.append(quote_text.text)
temp.append(quote_author.text)
quote_content.append(temp)
write_csv(quote_head,quote_content,quote_path)
三.爬取京东网站上的感兴趣书籍信息
代码
driver = webdriver.Chrome("E:\GoogleDownload\chromedriver_win32\chromedriver.exe")
driver.set_window_size(1920,1080)
# 京东网站
driver.get("https://www.jd.com/")
# 输入需要查找的关键字
key=driver.find_element_by_id("key").send_keys("python编程")
time.sleep(1)
# 点击搜素按钮
button=driver.find_element_by_class_name("button").click()
time.sleep(1)
# 获取所有窗口
windows = driver.window_handles
# 切换到最新的窗口
driver.switch_to.window(windows[-1])
time.sleep(1)
# js语句
js = 'return document.body.scrollHeight'
# 获取body高度
max_height = driver.execute_script(js)
max_height=(int(max_height/1000))*1000
# 当前滚动条高度
tmp_height=1000
# 所有书籍的字典
res_dict={}
# 需要爬取的数量
num=200
while len(res_dict)<num:
# 当切换网页后重新设置高度
tmp_height = 1000
while tmp_height < max_height:
# 向下滑动
js = "window.scrollBy(0,1000)"
driver.execute_script(js)
tmp_height += 1000
# 书籍列表
J_goodsList = driver.find_element_by_id("J_goodsList")
ul = J_goodsList.find_element_by_tag_name("ul")
# 所有书籍
res_list = ul.find_elements_by_tag_name("li")
# 把没有记录过的书籍加入字典
for res in res_list:
# 以书名为键,价格为值
# 两种方式获取指定标签值
res_dict[res.find_element_by_class_name('p-name').find_element_by_tag_name('em').text] \
= res.find_element_by_xpath("//div[@class='p-price']//i").text
if len(res_dict)==num:
break
time.sleep(2)
if len(res_dict) == num:
break
# 下一页按钮所在父标签
J_bottomPage=driver.find_element_by_id("J_bottomPage")
# 下一页按钮
next_button=J_bottomPage.find_element_by_class_name("pn-next").click()
# 切换窗口
windows = driver.window_handles
driver.switch_to.window(windows[-1])
time.sleep(3)
# 表头
csvHeaders = ['书名','价格']
# 所有书籍
csvRows=[]
# 书籍
row=[]
# 字典转列表
for key,value in res_dict.items():
row.append(key)
row.append(value)
csvRows.append(row)
row=[]
# 保存爬取结果
with open('./output/jd_books.csv', 'w', newline='') as file:
fileWriter = csv.writer(file)
fileWriter.writerow(csvHeaders)
fileWriter.writerows(csvRows)
结果
四.总结
Selenium是一系列基于Web的自动化工具,通过本次实验对其有了进一步的了解.