- # 导入 selenium 请求库
- from selenium import webdriver
- # 导入键盘 Keys
- from selenium.webdriver.common.keys import Keys
- import time
- '''
- 驱动浏览器的两种方式
- '''
- # 第一种直接去 Script 文件夹中查找驱动
- driver = webdriver.Chrome()
- #5 秒后自动关闭网页
- #time.sleep(5)
- #driver.close()
- # 第二种填写驱动路径
- #webdriver.Chrome(r'D:\chromedriver.exe')
- #try 检测代码块保证程序不报错
- try:
- #隐式等待
- driver.implicitly_wait(10)
- #往京东主页发送请求
- driver.get('https://www.jd.com/')
- #通过 id 查找 input 输入框
- #在京东主页详情页选择输入框找到 key
- input_tag = driver.find_element_by_id('key')
- #send_keys 为当前标签传值
- input_tag.send_keys('华为')
- #按键盘的回车键
- input_tag.send_keys(Keys.ENTER)
- time.sleep(3)
- '''
- 爬取京东商品信息:
- 华为
- 名称
- url
- 价格
- 评价
- '''
- #element 找一个
- #elements 找多个
- #查找所有的商品列表
- good_list = driver.find_elements_by_class_name('gl-item')
- #print(good_list)
- #循环遍历每一个商品
- for good in good_list:
- #通过属性选择器查找商品详情页 url
- #url
- good_url = good.find_element_by_CSS_selector('.p-img a').get_attribute('href')
- print(good_url)
- #名称
- good_name = good.find_element_by_css_selector('.p-name em').text
- print(good_name)
- #价格
- good_price = good.find_element_by_class_name('p-price').text
- print(good_price)
- #评价数
- good_commit = good.find_element_by_class_name('p-commit').text
- print(good_commit)
- str1 = f'''
- url:{good_url}
- 名称:{good_name}
- 价格:{good_price}
- 评价:{good_commit}
- \n
- '''
- # 把商品信息写入文本中
- with open('jd.txt','a',encoding='utf-8') as f:
- f.write(str1)
- time.sleep(10)
- # 捕获异常
- except Exception as e:
- print(e)
- # 最终都会把驱动浏览器关掉
- finally:
- driver.close()
来源: http://www.bubuko.com/infodetail-3106407.html