Python使用Selenium+BeautifulSoup爬取淘宝搜索页

yipeiwu_com6年前Python爬虫

使用Selenium驱动chrome页面,获得淘宝信息并用BeautifulSoup分析得到结果。

使用Selenium时注意页面的加载判断,以及加载超时的异常处理。

import json
import re
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Chrome()
# 浏览器需要多次使用,所以单独拿出来。设置一个最长的等待时间,等待目标加载完成
wait = WebDriverWait(browser, 10)


def search(keyword):
 # wait容易出现加载时间长的问题,因此用try来捕捉异常
 try:
 browser.get('https://www.taobao.com')
 # 加载需要一定时间的,设置了等待时间,等待加载
 # 输入按钮的加载等待
 input = wait.until(
  # 设置加载目标,它是一个选择器,参数是需要选择方式和等待加载的内容
  EC.presence_of_element_located((By.CSS_SELECTOR, "#q")) # 选择CSS选择器和选择内容
 )
 # 提交按钮
 submit = wait.until(
  # EC后面是选择条件,按钮的加载条件最好的是element_to_be_clickable,意思为元素可以点击的
  EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_TSearchForm > div.search-button > button"))
 )
 input.send_keys(keyword) # send_keys对输入框输入内容
 submit.click() # 提交搜索内容,进入下一个页面
 # 等待页码元素加载完成,并返回最大页码数
 total = wait.until(
  EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.total"))
 )
 # 等待加载完成后获取信息
 get_products()
 return total.text
 except TimeoutException:
 # 超时后重新请求,因此递归调用
 return search()


def next_page(page_number):
 try:
 # 页码输入框和翻页按钮
 input = wait.until(
  EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > input"))
 )
 # 提交按钮
 submit = wait.until(
  EC.element_to_be_clickable(
  (By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit"))
 )
 input.clear()
 input.send_keys(page_number)
 submit.click()
 # 判断翻页成功
 wait.until(
  EC.text_to_be_present_in_element((By.CSS_SELECTOR,
      '#mainsrp-pager > div > div > div > ul > li.item.active > span'),
      str(page_number)))
 get_products()
 except TimeoutException:
 return next_page(page_number)


def get_products():
 # 判断单个页面是否被加载出来
 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .items .item')))
 html = browser.page_source # 获取页面源代码,所有的
 # 使用BS进行分析
 soup = BeautifulSoup(html, 'lxml')
 items = soup.select('#mainsrp-itemlist .items .item')
 for item in items:
 image = item.select('.pic .img')[0]['data-src']
 price = item.select('.price strong')[0].text
 deal = item.select('.deal-cnt')[0].text[:-3]
 title = item.select('.title')[0].text.strip()
 shop = item.select('.shop')[0].text.strip()
 location = item.select('.location')[0].text
 product = {
  'image': image,
  'price': price,
  'deal': deal,
  'title': title,
  'shop': shop,
  'location': location
 }
 save_text(product) # 下载内容


def save_text(product):
 # 保存为txt文件,a追加写模式,编码模式utf-8
 with open('text.txt', 'a', encoding='utf-8') as f:
 # 使用JSON把字典转换为str格式,加换行符
 f.write(json.dumps(product, ensure_ascii=False) + '\n')
 f.close()


def main():
 # 通过关键字在淘宝进行搜索
 total = search('美食')
 # 用正则提取页码数字
 total = int(re.compile('(\d+)').search(total).group(1))
 # 翻页
 for i in range(2, total+1): # 循环包含前,不包含尾
 next_page(i)
 browser.close()


if __name__ == '__main__':
 main()

更多内容请参考专题《python爬取功能汇总》进行学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python妹子图简单爬虫实例

本文实例讲述了python妹子图简单爬虫实现方法。分享给大家供大家参考。具体如下: #!/usr/bin/env python #coding: utf-8 import urlli...

Python爬取网易云音乐上评论火爆的歌曲

Python爬取网易云音乐上评论火爆的歌曲

前言 网易云音乐这款音乐APP本人比较喜欢,用户量也比较大,而网易云音乐之所以用户众多和它的歌曲评论功能密不可分,很多歌曲的评论非常有意思,其中也不乏很多感人的评论。但是,网易云音乐并没...

python 爬取学信网登录页面的例子

python 爬取学信网登录页面的例子

我们以学信网为例爬取个人信息 **如果看不清楚 按照以下步骤:** 1.火狐为例 打开需要登录的网页–> F12 开发者模式 (鼠标右击,点击检查元素)–点击网络 –>需要...

详解Python3网络爬虫(二):利用urllib.urlopen向有道翻译发送数据获得翻译结果

详解Python3网络爬虫(二):利用urllib.urlopen向有道翻译发送数据获得翻译结果

上一篇内容,已经学会了使用简单的语句对网页进行抓取。接下来,详细看下urlopen的两个重要参数url和data,学习如何发送数据data 一、urlopen的url参数 Agent...

python3第三方爬虫库BeautifulSoup4安装教程

python3第三方爬虫库BeautifulSoup4安装教程

Python3安装第三方爬虫库BeautifulSoup4,供大家参考,具体内容如下 在做Python3爬虫练习时,从网上找到了一段代码如下: #使用第三方库BeautifulSou...