爬取淘宝商品信息,基于selenium工具,基本思路:使用selenium打开浏览器进入淘宝页面并搜索管检测,等待页面加载完毕,在网页源代码中寻找信息。
用于个人学习笔记,错误之处请指正。在代码中有详细注释。
1 准本工作
寻找网址和搜索关键词,用于构造URL。
需要使用selenium、pyquery和urllib库。
2 实现步骤
2.1 导包
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote
2.2 构造浏览器对象和关键词
# 构造请求
browser = webdriver.Edge() # 狗在一个Edge对象
wait = WebDriverWait(browser, 10) # 等待时间
KEYWORD = 'ipad' # 关键词
2.3 获取商品列表
def index_page(page):
"""抓取索引页面 page:页码"""
print(f"正在爬取{page}页")
try:
url = ('https://s.taobao.com/search?_input_charset=utf-8&commend=all&'
'ie=utf8&initiative_id=tbindexz_20170306&page=1&q=') + quote(KEYWORD)
browser.get(url) # 请求网页
if page > 1:
# 等待跳转页码的输入框出现
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, '#mainscrp-pager div.form > input')))
# 等待跳转页面的“确定”按钮可点击
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager div.form > span.btn,J_Submit')))
input.clear() # 清楚代码框内容
input.send_keys(page) # 输入指定的页码
submit.click() # 点击“确定”按钮
# 等待页面跳转到指定页码
wait.until(
EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'),
str(page)))
# 等待商品出现
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.m-itemlist .items .item')))
# get_products() # 获取商品
except TimeoutException:
print("cuowu")
2.4 解析商品信息
def get_products():
html = browser.page_source # 获取网页源代码
doc = pq(html) # 构造pq对象
items = doc('#mainsrp-itemlist .items .item').items() # 从源代码中获取信息
for item in items:
product = {
'image': item.find('.pic .img').attr('data-src'), # 使用find方法寻找
'price': item.find('.price').text(),
'deal': item.find('.deal-cnt').text(),
'title': item.find('.title').text(),
'shop': item.find('.shop').text(),
}
print(product)
# save_to_mongo(product) # 保存数据
2.5 保存信息
def save_to_txt(product):
with open('taobao_data.txt', 'a', encoding='utf-8') as file:
file.write(product)
3 完整代码
# 使用selenium来模拟浏览器操作,抓取淘宝的商品信息
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from urllib.parse import quote
from pyquery import PyQuery as pq
# 构造请求
browser = webdriver.Edge() # 狗在一个Edge对象
wait = WebDriverWait(browser, 10) # 等待时间
KEYWORD = 'ipad' # 关键词
def index_page(page):
"""抓取索引页面 page:页码"""
print(f"正在爬取{page}页")
try:
url = ('https://s.taobao.com/search?_input_charset=utf-8&commend=all&'
'ie=utf8&initiative_id=tbindexz_20170306&page=1&q=') + quote(KEYWORD)
browser.get(url) # 请求网页
if page > 1:
# 等待跳转页码的输入框出现
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, '#mainscrp-pager div.form > input')))
# 等待跳转页面的“确定”按钮可点击
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, '#mainsrp-pager div.form > span.btn,J_Submit')))
input.clear() # 清楚代码框内容
input.send_keys(page) # 输入指定的页码
submit.click() # 点击“确定”按钮
# 等待页面跳转到指定页码
wait.until(
EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#mainsrp-pager li.item.active > span'),
str(page)))
# 等待商品出现
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.m-itemlist .items .item')))
# get_products() # 获取商品
except TimeoutException:
print("cuowu")
def get_products():
html = browser.page_source # 获取网页源代码
doc = pq(html) # 构造pq对象
items = doc('#mainsrp-itemlist .items .item').items() # 从源代码中获取信息
for item in items:
product = {
'image': item.find('.pic .img').attr('data-src'), # 使用find方法寻找
'price': item.find('.price').text(),
'deal': item.find('.deal-cnt').text(),
'title': item.find('.title').text(),
'shop': item.find('.shop').text(),
}
print(product)
# save_to_mongo(product) # 保存数据
def save_to_txt(product):
with open('taobao_data.txt', 'a', encoding='utf-8') as file:
file.write(product)
if __name__ == '__name__':
index_page(1) #抓取第一页的