本次爬取用到的知识点有:
1. selenium
2. pymysql
3 pyquery
正文
1. 分析目标网站
1. 打开某宝首页, 输入"男装"后点击"搜索", 则跳转到"男装"的搜索界面.
2. 空白处"右击"再点击"检查"审查网页元素, 点击"Network".
1) 找到对应的URL, URL里的参数正是Query String Parameters的参数, 且请求方式是GET
2) 我们请求该URL得到内容就是"Response"里的内容, 那么点击它来确认信息.
3) 下拉看到"男装"字样, 那么再往下找, 并没有发现有关"男装"的商品信息.
4) 任意复制一个商品信息, 空白处右击再点击"查看网页源代码", 在源码查找该商品, 即可看到该商品的信息.
5) 对比网页源代码和"Response"响应内容, 发现源代码<script>..........</script>中的商品信息被替换, 这便是采用了JS加密
6) 如果去请求上面的URL, 得到的则是加密过的信息, 这时就可以利用Selenium库来模拟浏览器, 进而得到商品信息.
2. 获取单个商品界面
1. 请求网站
# -*- coding: utf-8 -*-
from selenium import webdriver #从selenium导入浏览器驱动
browser = webdriver.Chrome() #声明驱动对象, 即Chrome浏览器
def get_one_page():
'''获取单个页面'''
browser.get("https://www.xxxxx.com") #请求网站
2. 输入"男装", 在输入之前, 需要判断输入框是否存在, 如果存在则输入"男装", 不存在则等待显示成功.
# -*- coding: utf-8 -*-
from selenium import webdriver
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()
def get_one_page():
'''获取单个页面'''
browser.get("https://www.xxxxx.com")
input = WebDriverWait(browser,10).until( #等待判断
EC.presence_of_element_located((By.CSS_SELECTOR,"#q"))) #若输入框显示成功,则获取,否则等待
input.send_keys("男装") #输入商品名称
3. 下一步就是点击"搜索"按钮, 按钮具有属性: 可点击, 那么加入判断条件.
# -*- coding: utf-8 -*-
from selenium import webdriver
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()
def get_one_page():
'''获取单个页面'''
browser.get("https://www.xxxxx.com")
input = WebDriverWait(browser,10).until(
EC.presence_of_element_located((By.CSS_SELECTOR,"#q"))) #
input.send_keys("男装")
button = WebDriverWait(browser,10).until( #等待判断
EC.element_to_be_clickable((By.CSS_SELECTOR,"#J_TSearchForm > div.search-button > button"))) #若按钮可点击, 则获取, 否则等待
button.click()