一、Selenium介绍与配置
- Selenium简介
Selenium 是ThoughtWorks专门为Web应用程序编写的一个验收测试工具。Selenium测试直接运行在浏览器中,可以模拟真实用户的行为。支持的浏览器包括IE(7、8、9)、Mozilla Firefox、Mozilla Suite等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好地工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。 - selenium配置
pip install selenium
要使用selenium去调用浏览器,还需要一个驱动,不同浏览器的webdriver需要独立安装
驱动下载地址:https://www.selenium.dev/documentation/webdriver/getting_started/install_drivers/
二、启动浏览器并打开百度搜索
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'D:\Download\chromedriver.exe')
driver.get("https://www.baidu.com")
运行之后会打开谷歌浏览器,并打开百度搜索页面
在开发者工具中找到输入框
填充搜索框
p_input = driver.find_element_by_id('kw')
print(p_input)
print(p_input.location)
print(p_input.size)
print(p_input.send_keys('海贼王'))
print(p_input.text)
location,是元素的位置;
size是元素的大小
send_keys是给元素传入值
这里,我们再传入“海贼王”之后,会自动展开搜索
我们在传入搜索值之后,页面切换了,但是,并没有进行搜索,我们还差一步搜索,所以我们可以使用
用另一个input,也就是按钮的点击事件来实现;或者是form表单的提交事件
p_btn = driver.find_element_by_id('su')
p_btn.click()
执行结果
三、爬取动态网页数据
- 网页数据分析
在开发者工具中查看每一组名言的位置:
可以发现每一组名言都是在class="quote"的div中,且名句在class="text"的标签中,作者在class="author"的small标签中。 - 翻页分析
可发现Next按钮只有href属性,无法定位。但可以通过查找网页最后一个有aria-hidden属性的span标签,进行点击以跳转到下一页。 - 爬取数据
from selenium.webdriver import Chrome
import time
import csv
driver = webdriver.Chrome(executable_path=r'D:\Download\chromedriver.exe')
driver.get('http://quotes.toscrape.com/js/')
sayingAndAuthor = []
n = 5
for i in range(0, n):
div_list = driver.find_elements_by_class_name('quote')
for div in div_list:
saying = div.find_element_by_class_name('text').text
author = div.find_element_by_class_name('author').text
info = [saying, author]
sayingAndAuthor.append(info)
print('成功爬取第' + str(i + 1) + '页')
if i == n-1:
break
driver.find_elements_by_css_selector('[aria-hidden]')[-1].click()
time.sleep(2)
with open('D:\Saying.txt', 'w', encoding='utf-8')as fp:
fileWrite = csv.writer(fp)
fileWrite.writerow(['名言', '名人']) # 写入表头
fileWrite.writerows(sayingAndAuthor)
driver.close()
爬取结果:
四、爬取京东网站书籍信息
爬取计算机网络这本书的信息:
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
from lxml import etree
import csv
driver = webdriver.Chrome(executable_path=r'D:\Download\chromedriver.exe')
driver.get('https://www.jd.com/')
driver.maximize_window()
driver.find_element_by_id('key').send_keys('计算机网络', Keys.ENTER)
def get_onePage_info(web):
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(2)
page_text = driver.page_source
# 进行解析
tree = etree.HTML(page_text)
li_list = tree.xpath('//li[contains(@class,"gl-item")]')
book_infos = []
for li in li_list:
book_name = ''.join(
li.xpath('.//div[@class="p-name"]/a/em/text()')) # 书名
price = '¥' + \
li.xpath('.//div[@class="p-price"]/strong/i/text()')[0] # 价格
author_span = li.xpath('.//span[@class="p-bi-name"]/a/text()')
if len(author_span) > 0: # 作者
author = author_span[0]
else:
author = '无'
store_span = li.xpath(
'.//span[@class="p-bi-store"]/a[1]/text()') # 出版社
if len(store_span) > 0:
store = store_span[0]
else:
store = '无'
img_url_a = li.xpath('.//div[@class="p-img"]/a/img')[0]
if len(img_url_a.xpath('./@src')) > 0:
img_url = 'https' + img_url_a.xpath('./@src')[0] # 书本图片地址
else:
img_url = 'https' + img_url_a.xpath('./@data-lazy-img')[0]
one_book_info = [book_name, price, author, store, img_url]
book_infos.append(one_book_info)
return book_infos
def main():
driver = webdriver.Chrome(executable_path=r'D:\Download\chromedriver.exe')
driver.get('https://www.jd.com/')
driver.maximize_window()
driver.find_element_by_id('key').send_keys('计算机网络', Keys.ENTER) # 找到输入框输入,回车
time.sleep(2)
all_book_info = []
for i in range(0, 3):
all_book_info += get_onePage_info(web)
print('爬取第' + str(i+1) + '页成功')
driver.find_element_by_class_name('pn-next').click() # 点击下一页
time.sleep(2)
with open('D:\计算机网络.csv', 'w', encoding='utf-8')as fp:
writer = csv.writer(fp)
writer.writerow(['书名', '价格', '作者', '出版社', '预览图片地址'])
writer.writerows(all_book_info)
if __name__ == '__main__':
main()
爬取结果:
总结
通过对Selenium 的学习,成功爬取了动态网站的数据信息。
参考
https://zhuanlan.zhihu.com/p/331712873
https://blog.csdn.net/YangMax1/article/details/121704916