使用自动化工具Selenium,模拟浏览器动态抓取淘宝网页数据
1.页面分析
# 获取主页的搜索框
By.CSS_SELECTOR, '#q'
# 获取搜索按钮
#J_TSearchForm > div.search-button > button
# 获取总页码
#mainsrp-pager > div > div > div > div.total
# 获取页码输入框
#mainsrp-pager > div > div > div > div.form > input
# 获取确定按钮
#mainsrp-pager > div > div > div > div.form > span.btn.J_Submit
# 获取高亮显示
#mainsrp-pager > div > div > div > ul > li.item.active > span
2. 解析提取网页数据
# 判断元素是否加载完成
#mainsrp-itemlist .items .item
# 使用pqquery进行数据提取
获取全部的: '#mainsrp-itemlist .items .item'
然后再循环取每个商品的信息:
图片image: '.pic .img'.attr('data-src') #图片是动态加载的,直接获取src属性可能获取不到
价格price: '.price'
购买数deal: '.deal-cnt'
标题title: '.title'
店铺shop: '.shop'
地址location: '.location'
3.保存数据(这里保存到文件中)
具体代码:
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
import re
from pyquery import PyQuery as pq
# 全局变量
browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)
KEYWORD = '美食'
def search():
""""""获取主页并抓取第一页数据""""""
try:
# 打开浏览器及淘宝首页
browser.get('https://www.taobao.com/')
# 获取搜索输入框及搜索按钮
input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#q')))
submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_TSearchForm > div.search-button > button')))
# 输入搜索关键字并点击搜索按钮
input.send_keys(KEYWORD)
submit.click()
# 获取总页码数,并返回结果
total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.total')))
parse_page()
return total.text
except TimeoutError:
return search()
def next_page(page):
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)
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)))
parse_page()
except TimeoutError:
return next_page(page)
def parse_page():
"""页面数据处理"""
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .items .item')))
# 获取网页源码
html = browser.page_source
# print(html)
# 使用pyquery库来解析提取数据
doc = pq(html)
items = doc('#mainsrp-itemlist .items .item').items()
for item in items:
message = {
'image': "http:" + item.find('.pic .img').attr('data-src'),
'price': item.find('.price').text(),
'deal': item.find('.deal-cnt').text()[:-3],
'title': item.find('.title').text(),
'shop': item.find('.shop').text(),
'location': item.find('.location').text()
}
# print(message)
# 将提取的数据写入文档
with open(KEYWORD + ".txt", "a") as f:
f.write(str(message) + "\n")
def main():
total = search() # 共100页
# 使用正则匹配提取数字100,并转为整型
total = int(re.compile('(\d+)').search(total).group(1))
# print(total) # for test
for page in range(2, total + 1):
next_page(page)
if __name__ == "__main__":
main()