Python 基于Selenium实现 * 页信息的爬取

作者:Max_Shy 时间:2023-10-31 12:00:22 

一、Selenium介绍与配置

1.Selenium简介

Selenium 是ThoughtWorks专门为Web应用程序编写的一个验收测试工具。Selenium测试直接运行在浏览器中,可以模拟真实用户的行为。支持的浏览器包括IE(7、8、9)、Mozilla Firefox、Mozilla Suite等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好地工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。

2. Selenium+Python环境配置


pip install selenium

二、网页自动化测试

1.启动浏览器并打开百度搜索


from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')

2.定位元素

在开发者工具中找到输入框

Python 基于Selenium实现 * 页信息的爬取

输入要查询的值并通过button点击事件实现


input_btn = web.find_element_by_id('kw')
input_btn.send_keys('原神', Keys.ENTER)

测试:

Python 基于Selenium实现 * 页信息的爬取

三、爬取 * 页的名人名言

1. 网页数据分析

在开发者工具中查看每一组名言(名言+名人)的位置:

Python 基于Selenium实现 * 页信息的爬取

现每一组名言都是在class="quote"的div中,并且没有其他class="quote的标签。

Python 基于Selenium实现 * 页信息的爬取

且名句在class="text"的<span>标签中,作者在class="author"的small标签中。

2. 翻页分析

在开发者工具中查看Next翻页按钮

Python 基于Selenium实现 * 页信息的爬取

可发现Next按钮只有href属性,无法定位。但可以通过查找网页最后一个有aria-hidden属性的span标签,进行点击以跳转到下一页。

3.爬取数据的存储

爬取后的数据需要存储至csv文件中,编写代码如下:


with open('Saying.csv', 'w', encoding='utf-8')as fp:
   fileWrite = csv.writer(fp)
   fileWrite.writerow(['名言', '名人'])  
   fileWrite.writerows(sayingAndAuthor)
web.close()

4. 爬取数据

代码准备:


from selenium.webdriver import Chrome
import time
import csv

web = Chrome(r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")

web.get('http://quotes.toscrape.com/js/')

sayingAndAuthor = []
n = 5
for i in range(0, n):
   div_list = web.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
   web.find_elements_by_css_selector('[aria-hidden]')[-1].click()
   time.sleep(2)

with open('Saying.csv', 'w', encoding='utf-8')as fp:
   fileWrite = csv.writer(fp)
   fileWrite.writerow(['名言', '名人'])   # 写入表头
   fileWrite.writerows(sayingAndAuthor)
web.close()

爬取结果:

Python 基于Selenium实现 * 页信息的爬取

四、爬取京东网站书籍信息

爬取某个关键字书籍的前三页书籍信息,本文以计算机图形学为例

1.进入网页并搜索计算机图形学


from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys

web = Chrome(r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")

web.get('https://www.jd.com/')
web.maximize_window()
web.find_element_by_id('key').send_keys('计算机图形学', Keys.ENTER)  # 找到输入框输入,回车

Python 基于Selenium实现 * 页信息的爬取

成功。

2.网页分析

使用开发者工具可查看每一个商品信息的位置

Python 基于Selenium实现 * 页信息的爬取

发现每一个商品信息都存在于class包含gl-item的li中。因此获取该页面下所有li,由此爬取书籍信息(包括书名和价格)。

3.翻页


web.find_element_by_class_name('pn-next').click()  # 点击下一页

4.数据保存


with open('计算机图形学.csv', 'w', encoding='utf-8')as fp:
   writer = csv.writer(fp)
   writer.writerow(['书名', '价格', '作者', '出版社', '预览图片地址'])
   writer.writerows(all_book_info)

5.代码准备


from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
from lxml import etree
import csv

web = Chrome(r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")
web.get('https://www.jd.com/')
web.maximize_window()
web.find_element_by_id('key').send_keys('计算机图形学', Keys.ENTER)  

def get_onePage_info(web):
   web.execute_script('window.scrollTo(0, document.body.scrollHeight);')
   time.sleep(2)
   page_text = web.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():
   web = Chrome(
       r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")

web.get('https://www.jd.com/')
   web.maximize_window()
   web.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) + '页成功')
       web.find_element_by_class_name('pn-next').click()  # 点击下一页
       time.sleep(2)
   with open('计算机图形学.csv', 'w', encoding='utf-8')as fp:
       writer = csv.writer(fp)
       writer.writerow(['书名', '价格', '作者', '出版社', '预览图片地址'])
       writer.writerows(all_book_info)

if __name__ == '__main__':
   main()

爬取结果

Python 基于Selenium实现 * 页信息的爬取

成功

五、总结

本文通过Selenium和webdrive等库,对 * 页的信息进行爬取。 

来源:https://blog.csdn.net/YangMax1/article/details/121704916

标签:Python,Selenium,网页信息,爬取
0
投稿

猜你喜欢

  • 新装MySql后登录出现root帐号提示mysql ERROR 1045 (28000): Access denied for use的解决办法

    2024-01-21 13:48:06
  • MySQL 编码机制

    2024-01-14 23:52:38
  • ThinkPHP中__initialize()和类的构造函数__construct()用法分析

    2023-07-08 01:26:24
  • 关于base64编码的原理及实现方法分享

    2023-08-31 07:34:40
  • django在保存图像的同时压缩图像示例代码详解

    2021-09-21 15:42:46
  • 数据库设计工具MySQL Workbench使用教程(超级详细!)

    2024-01-29 01:26:22
  • python中Switch/Case实现的示例代码

    2021-09-18 22:03:39
  • 解析如何加快mysql编译的速度

    2024-01-15 07:26:55
  • 五大提高ASP运行效率的技巧

    2007-09-20 13:15:00
  • 关于SQL Server中bit类型字段增删查改的一些事

    2024-01-13 10:07:45
  • 超大数据量存储常用数据库分表分库算法总结

    2024-01-28 01:44:38
  • Mysql保持现有内容在后面增加内容的sql语句

    2024-01-21 07:11:01
  • python列表详情

    2023-12-29 01:59:06
  • Python爬虫 bilibili视频弹幕提取过程详解

    2023-07-05 06:41:25
  • python变量作用域与列表入门详解

    2022-09-05 05:58:27
  • 使用python无账号无限制获取企查查信息的实例代码

    2021-09-23 20:26:10
  • oracle命令行删除与创建用户

    2008-01-02 17:01:00
  • Go语言map元素的删除和清空

    2024-02-05 10:42:25
  • Python for Informatics 第11章 正则表达式(一)

    2021-01-27 06:43:43
  • js拖拽效果的原理及实现

    2024-04-10 10:43:29
  • asp之家 网络编程 m.aspxhome.com