先给大家介绍下python3 selenium使用

其实这个就相当于模拟人的点击事件来连续的访问浏览器。如果你玩过王者荣耀的话在2016年一月份的版本里面就有一个bug。

安卓手机下载一个按键精灵就可以在冒险模式里面设置按键,让手机自动玩闯关,一局19个金币,一晚上就一个英雄了。不过

程序员也不是吃素的。给一个星期设置了大概4000金币上限。有兴趣的可以去试试。(注:手机需要root)

进入正题:

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.common.keys import Keys

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.support.wait import WebDriverWait

在写之前需要下载selenium模块

brguge=webdriver.Chrome()#声明驱动对象

try:

brguge.get('https://www.baidu.com')#发送get请求

input=brguge.find_element_by_id('kw')#找到目标

input.send_keys('python')#输入python关键字

input.send_keys(Keys.ENTER)#敲入回车

wait=WebDriverWait(brguge,10)#等待元素加载出来

wait.until(EC.presence_of_element_located(By.ID,'content_left'))#加载

print(brguge.current_url)#输出搜索的路径

print(brguge.get_cookie())#输出cookie

print(brguge.page_source)#输出结果源代码

finally:

brguge.close()#关闭谷歌浏览器

下面是一些selenium模块的基本用法

查找元素

单个元素

(from selenium import webdriver)

brguge.find_element_by_id('q')用这个元素找id是q的元素

brguge.find_element_by_css_selector('#q')找css样式是q的

brguge.find_element_by_xpath('//*[ @id="q"]')三个效果一样

brguge.find_element_by_name()通过name来查找

brguge.find_element_by_link_text()通过link来查找

brguge.find_element_by_partial_link_text()

brguge.find_element_by_tag_name()

brguge.find_element_by_class_name()通过class查找

from selenium import webdriver

from selenium.webdriver.common.by import By

brguge.find_element(By.ID,'Q')通用查找方式

多个元素(find_elements)加了个s

他会以列表的形式打印出来

brguge.find_elements_by_css_selector('.service-bd li')css样式为li的元素

brguge.find_elements(By.css_selector,'.service-bd li')两个作用一样

(利用索引就可以获取单个或多个元素了)

元素交互操作(获取元素然后再给他指令)

选择输入框 --》send_keys('输入文字')--》clear()清空输入框--在输入别的--》找到搜索--》click(点击)

input.clear()清空按钮

交互动作(将动作附加到动作链中串行执行)

switch_to_frame('iframeResult')

用css样式分别找到两个要交互

调用ActionChains(调用谷歌的)

drag_and_drop(source,target)第一个到第二个上面

perform()

下面看下python3通过selenium爬虫获取到dj商品的实例代码。

具体代码如下所示:

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.common.keys import Keys

from selenium.webdriver.support.wait import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.chrome.options import Options

from selenium.common.exceptions import NoSuchElementException

from lxml import etree

import time, json

'''遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!'''

JD_URL_Login = "https://www.jd.com/"

class CustomizeException(Exception):

def __init__(self, status, msg):

self.status = status

self.msg = msg

class JD:

def __init__(self):

self.browser = None

self.__init_browser()

def __init_browser(self):

options = Options()

options.add_argument("--headless")

options.add_experimental_option('excludeSwitches', ['enable-automation'])

# 设置为无图模式

options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})

self.browser = webdriver.Chrome(options=options)

# 设置浏览器最大化窗口

self.browser.maximize_window()

# 隐式等待时间为3s

self.browser.implicitly_wait(3)

self.browser.get(JD_URL_Login)

self.wait = WebDriverWait(self.browser, 10)

def __search_goods(self, goods):

'''搜索商品的方法'''

self.file = open("jd-{}.json".format(goods), "a", encoding="utf-8")

self.wait.until(EC.presence_of_all_elements_located((By.ID, "key")))

serach_input = self.browser.find_element_by_id("key")

serach_input.clear()

serach_input.send_keys(goods, Keys.ENTER)

def __get_goods_info(self, page_source):

'''从网页源码中获取到想要的数据'''

selector_html = etree.HTML(page_source)

# 商品名字 不要获取title属性,以后再改吧,最好是获取到商品名的文本内容

goods_name = selector_html.xpath("//div[@class='gl-i-wrap']//div[contains(@class,'p-name')]/a/@title")

# 商品价格

goods_price = selector_html.xpath("//div[@class='gl-i-wrap']//div[@class='p-price']/strong/i/text()")

# 商品评价数量

comment_num_selector = selector_html.xpath("//div[@class='p-commit']/strong")

comment_num = [selector.xpath("string(.)") for selector in comment_num_selector]

# 商品店铺

shop_name = selector_html.xpath("//a[@class='curr-shop']/text()")

goods_zip = zip(goods_name, goods_price, comment_num, shop_name)

for goods_info in goods_zip:

dic = {}

dic["goods_name"] = goods_info[0]

dic["goods_price"] = goods_info[1]

dic["comment_num"] = goods_info[2]

dic["shop_name"] = goods_info[3]

# print("商品名字>>:", goods_info[0])

# print("商品价格>>:", goods_info[1])

# print("商品评价数量>>:", goods_info[2])

# print("商品店铺>>:", goods_info[3])

# print("*" * 100)

yield dic

def __swipe_page(self):

'''上下滑动页面,将完整的网页源码返回'''

height = self.browser.execute_script("return document.body.scrollHeight;")

js = "window.scrollTo(0,{});".format(height)

self.browser.execute_script(js)

while True:

time.sleep(1)

now_height = self.browser.execute_script("return document.body.scrollHeight;")

if height == now_height:

return self.browser.page_source

js = "window.scrollTo({},{});".format(height, now_height)

self.browser.execute_script(js)

height = now_height

def __is_element_exists(self, xpath):

'''检测一个xpath是否能够找到'''

try:

self.browser.find_element_by_xpath(xpath=xpath)

return True

except NoSuchElementException:

return False

def __click_next_page(self):

'''点击下一页,实现翻页功能'''

self.wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, "pn-next")))

xpath = "//a[@class='pn-next']"

if not self.__is_element_exists(xpath):

raise CustomizeException(10000, "该商品访问完毕")

self.browser.find_element_by_xpath(xpath).click()

def __write_to_json(self, dic: dict):

data_json = json.dumps(dic, ensure_ascii=False)

self.file.write(data_json + "\n")

def run(self, goods):

self.__search_goods(goods)

n = 1

while True:

print("正在爬取商品 ---第{}页......".format(goods, n))

time.sleep(3)

html = self.__swipe_page()

for dic in self.__get_goods_info(html):

self.__write_to_json(dic)

try:

self.__click_next_page()

except CustomizeException:

try:

goods = goods_list.pop(0)

self.run(goods)

except IndexError:

return

n += 1

def __del__(self):

self.browser.close()

self.file.close()

if __name__ == '__main__':

jd = JD()

goods_list = ["纯牛奶", "酸奶", "奶茶", "床上用品", "电磁炉", "电视", "小米笔记本", "华硕笔记本", "联想笔记本", "男士洗面奶", "女士洗面奶", "沐浴露", "洗发露",

"牙刷", "牙膏", "拖鞋", "剃须刀", "水手服", "运动服", "红龙果", "苹果", "香蕉", "洗衣液", "电饭煲"]

try:

goods = goods_list.pop(0)

except IndexError:

raise CustomizeException(20000, "goods_list不能为空")

try:

jd.run(goods)

finally:

del jd

python selenium爬虫代码示例_python3通过selenium爬虫获取到dj商品的实例代码相关推荐

  1. R语言使用tryCatch函数调试R代码实战:tryCatch函数运行正常R代码、tryCatch函数运行有错误(error)的R代码示例/tryCatch函数运行有警告(warning)的R代码示例

    R语言使用tryCatch函数调试R代码实战:tryCatch函数运行正常R代码.tryCatch函数运行有错误(error)的R代码示例/tryCatch函数运行有警告(warning)的R代码示例 ...

  2. python如何保存源文件_python自动保存百度盘资源到百度盘中的实例代码

    本实例的实现逻辑是,应用selenium UI自动化登录百度盘,读取存储百度分享地址和提取码的txt文档,打开百度盘分享地址,填入提取码,然后保存到指定的目录中 全部代码如下: # -*-coding ...

  3. python 怎么将数字转大写_Python将数字转化为中文大写的实例代码

    Python将阿拉伯数字转化为中文大写,关键点在于中间空多个0的问题. 这种情况下,采用拆分法则,将一个大数字,先拆分成整数部分和小数部分,再对整数部分按照仟.万.亿.兆分位拆分为四个字符串组成的Li ...

  4. python爬取音乐排行_python爬取网易云音乐热歌榜实例代码

    首先找到要下载的歌曲排行榜的链接,这里用的是: https://music.163.com/discover/toplist?id=3778678 然后更改你要保存的目录,目录要先建立好文件夹,例如我 ...

  5. python怎么让x轴45°展示_python opencv实现任意角度的透视变换实例代码

    本文主要分享的是一则python+opencv实现任意角度的透视变换的实例,具体如下: # -*- coding:utf-8 -*- import cv2 import numpy as np def ...

  6. python对逻辑回归进行显著性_python sklearn库实现简单逻辑回归的实例代码

    Sklearn简介 Scikit-learn(sklearn)是机器学习中常用的第三方模块,对常用的机器学习方法进行了封装,包括回归(Regression).降维(Dimensionality Red ...

  7. python压缩图片像素_python使用pil进行图像处理(等比例压缩、裁剪)实例代码

    PIL中设计的几个基本概念 1.通道(bands):即使图像的波段数,RGB图像,灰度图像 以RGB图像为例: 2.模式(mode):定义了图像的类型和像素的位宽.共计9种模式: 3.尺寸(size) ...

  8. python按键持续按下响应_python按键按住不放持续响应的实例代码

    在学习飞机大战(我也不知道为什么都拿这个练手),飞机左右控制都是按键按一次移动一次,不能按住一个键后持续移动,离开后停止移动. 为了解决这个,查看了参考手册,说让用pygame.key.set_rep ...

  9. php如何获取js文本框内的内容,js获取input标签的输入值(实例代码)

    代码说明: 部分标签和类是封装在框架内的,其效果和html标签类似,遇到此类标签时,按html标签来理解会容易些. 1,javascript代码 复制代码 代码示例: function InsertD ...

最新文章

  1. Windows 11 再惹“众怒”!网友:微软就是逼我去买新电脑!
  2. 年终盘点篇:2018年开源市场5大发展趋势
  3. Oracle TNSListener服务启动后自动停止问题
  4. CSS学习——基础分类整理
  5. 常用计算机服务,常用计算机端口对应的服务(The commonly used computer port corresponding service).doc...
  6. 在 Linux 下使用 RAID(二):使用 mdadm 工具创建软件 RAID 0 (条带化)
  7. functionclass[LeetCode]Path Sum II
  8. Halcon算子学习:sample_object_model_3d
  9. 分库分表学习总结(2)——数据库中间件MyCat学习总结之MyCat-Web原理介绍
  10. The constructor someMethod() is not accessible due to restriction on required library
  11. java.sql.SQLException: Access denied for user ‘root‘@‘hadoop001‘ (using password: YES)
  12. Vuex初级入门及简单案例
  13. js最基础知识回顾1(参数,函数,网页换肤)
  14. unity中的透视投影矩阵
  15. 计算机电源指示灯,为什么笔记本电脑电源指示灯一直闪?
  16. win10禁止计算机进入休眠,Win10怎么关闭系统休眠 Win10关闭系统休眠方法
  17. 环迅支付匠心独具,打造跨境收款解决新方式
  18. 抓取WebSocket推送的消息
  19. java继承a mya new c,java – 为什么外部类不能扩展内部类?
  20. 360云盘关闭一周后:国家版权局称值得肯定,是榜样

热门文章

  1. 大规模搜索+预训练,百度是如何落地的?
  2. centos7挂载nas存储_NAS同步百度云全攻略!一篇打尽win虚拟机、黑群、Docker操作演示...
  3. 使用mysql-proxy读写分离时的注意事项_mysql-proxy中Admin Plugin的使用以及读写分离的问题...
  4. 和java转换_java基础之 类型转换
  5. 花书+吴恩达深度学习(九)优化方法之二阶近似方法(牛顿法, CG, BFGS, L-BFGS)
  6. 机器学习-吴恩达-笔记-2-逻辑回归
  7. 【转载】Windows 10系统默认将画面显示比例调整至125%或150%,最高分辨率已经达到3840×2160(4K)这一级别。...
  8. PHP如何实现百万级数据导出
  9. Java自动化测试框架-10 - TestNG之测试结果篇(详细教程)
  10. c语言单片机串口通讯,单片机C语言之串口通信协议