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 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

python3爬虫-通过selenium获取到dj商品的更多相关文章

  1. python3爬虫-通过selenium获取TB商品

    from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from seleni ...

  2. Python3.x:selenium获取iframe内嵌页面的源码

    Python3.x:selenium获取iframe内嵌页面的源码 前言 在一些网页中经常会看到ifrmae/frame标签,iframe是嵌入式框架一般用来在已有的页面中嵌入另一个页面,当一个元素在 ...

  3. 小白学 Python 爬虫:Selenium 获取某大型电商网站商品信息

    目标 先介绍下我们本篇文章的目标,如图: 本篇文章计划获取商品的一些基本信息,如名称.商店.价格.是否自营.图片路径等等. 准备 首先要确认自己本地已经安装好了 Selenium 包括 Chrome ...

  4. python爬虫——用selenium爬取京东商品信息

    1.先附上效果图(我偷懒只爬了4页)  2.京东的网址https://www.jd.com/ 3.我这里是不加载图片,加快爬取速度,也可以用Headless无弹窗模式 options = webdri ...

  5. python3爬虫-通过requests获取安居客房屋信息

    import requests from fake_useragent import UserAgent from lxml import etree from http import cookiej ...

  6. 爬虫之selenium爬取京东商品信息

    import json import time from selenium import webdriver """ 发送请求 1.1生成driver对象 2.1窗口最大 ...

  7. python3 [爬虫实战] selenium 爬取安居客

    我们爬取的网站:https://www.anjuke.com/sy-city.html 获取的内容:包括地区名,地区链接: 安居客详情 一开始直接用requests库进行网站的爬取,会访问不到数据的, ...

  8. 【Python3爬虫】selenium入门

    selenium 是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Fire ...

  9. python3爬虫-通过selenium登陆拉钩,爬取职位信息

    from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from se ...

随机推荐

  1. Pwn with File结构体之利用 vtable 进行 ROP

    前言 本文以 0x00 CTF 2017 的 babyheap 为例介绍下通过修改 vtable 进行 rop 的操作 (:-_- 漏洞分析 首先查看一下程序开启的安全措施 18:07 haclh@u ...

  2. 612.1.002 ALGS4 | Analysis of Algorithms

    我们生活在大数的时代 培养数量级的敏感! Tip:见招拆招 作为工程师,你先要能实现出来. 充实基础,没有什么不好意思 哪怕不完美.但是有时候完成比完美更重要. 之后再去想优化 P.S.作者Rober ...

  3. Python 中单双引号

    TODO, 在python中, 其实单双引号还是有分别的, 具体是什么?

  4. Oracle EBS 应收发票取值

    SELECT ct.trx_number ,ctl.description ,fnd_flex_ext.get_segs('SQLGL' ,'GL#' ,gcc.chart_of_accounts_i ...

  5. 不同服务器数据库之间的数据定时同步到sql server (支持mysql,oracle数据库同步到sql server)

    1,在目标数据库新增服务器对象->连接到服务器->新建服务器连接 2,编写数据同步业务PROC ALTER PROC TestProc AS BEGIN --打开完全事物回滚 SET XA ...

  6. C++ 的继承与虚函数 读书笔记

    一.类与类之间关系: 1.类与类之间可能会存在共性. 2.类与类之间必定会有差异. 3.为也节约开发时间和代码量,我们在设计类时可以把类的共享抽象出来形成一个基础类(基类). 4.使用基类+差异生成一 ...

  7. MySQL字符存储:charset-unicode-sets

    https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-sets.html 10.10.1 Unicode Character Sets MyS ...

  8. [转]CentOS7增加或修改SSH端口号

    前言:开启某服务或软件的端口,要从该服务或软件监听的端口(多以修改配置文件为主),SeLinux和防火墙(FireWall)的安全策略下手.如果使用阿里云,腾讯等第三方服务器还需要对管理控制台的安全组 ...

  9. Office 365实现单点登录系列(2)—Azure AD Connect安装与配置

    前言 第一篇文章我已经为大家分享了在在Azure上搭建域控服务器的方法,如果大家本地已经有了域环境,可以直接从这一篇文章开始阅读.Azure AD Connect的前身是DirSync,是专门用于目录 ...

  10. Hadoop HBase概念学习系列之HBase里的宽表设计概念(表设计)(二十七)

    在下面这篇博文里,我给各位博客们,分享了创建HBase表,但这远不止打好基础. HBase编程 API入门系列之create(管理端而言)(8) 在关系型数据库里,表的高表和宽表是不存在的.在如HBa ...