双十一手剁完了吗?教你用Python再剁一遍(Python模拟登录,采集淘宝商品数据)
前言
11月4日,中国消费者协会在官网发布消费提示,提醒消费者“双十一”购物六点注意事项。主要内容就是对于双十一的“低价”不可迷信,提防商家套路。那么对于我们要怎么样才能选择真正的底价好货呢?
今天带大家使用python+selenium工具获取这些公开的商家数据,可以采集商品的价格和评价做对比
- python 3.8
- pycharm
- selenium
- csv
- time
- random
from selenium import webdriver import time # 时间模块, 可以用于程序的延迟 import random # 随机数模块 from constants import TAO_USERNAME1, TAO_PASSWORD1 import csv # 数据保存的模块
driver = webdriver.Chrome()
driver.get('https://www.taobao.com/') driver.implicitly_wait(10) # 设置浏览器的等待,加载数据 driver.maximize_window() # 最大化浏览器
首先,打开开发者工具;然后选择用左上角的工具选中搜索框,然后会帮我们定位到当前选中元素的标签;最后,右键,选择Copy,再选择Xpath语法
def search_product(keyword): driver.find_element_by_xpath('//*[@id="q"]').send_keys(keyword) time.sleep(random.randint(1, 3)) # 尽量避免人机检测 随机延迟 driver.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click() time.sleep(random.randint(1, 3)) # 尽量避免人机检测 随机延迟 word = input('请输入你要搜索商品的关键字:') # 调用商品搜索的函数 search_product(word)
用上面相同的方法,找到所需元素
driver.find_element_by_xpath('//*[@id="f-login-id"]').send_keys(TAO_USERNAME1) time.sleep(random.randint(1, 3)) # 尽量避免人机检测 随机延迟 driver.find_element_by_xpath('//*[@id="f-login-password"]').send_keys(TAO_PASSWORD1) time.sleep(random.randint(1, 3)) # 尽量避免人机检测 随机延迟 driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click() time.sleep(random.randint(1, 3)) # 尽量避免人机检测 随机延迟
对于本篇文章有疑问的同学可以加【资料白嫖、解答交流群:1136201545】
修改浏览器的部分属性, 绕过检测
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": """Object.defineProperty(navigator, 'webdriver', {get: () => false})"""})
def parse_data(): divs = driver.find_elements_by_xpath('//div[@class="grid g-clearfx"]/div/div') # 所有的div标签 for div in divs: try: info = div.find_element_by_xpath('.//div[@class="row row-2 title"]/a').text price = div.find_element_by_xpath('.//strong').text + '元' deal = div.find_element_by_xpath('.//div[@class="deal-cnt"]').text name = div.find_element_by_xpath('.//div[@class="shop"]/a/span[2]').text location = div.find_element_by_xpath('.//div[@class="location"]').text detail_url = div.find_element_by_xpath('.//div[@class="pic"]/a').get_attribute('href') print(info, price, deal, name, location, detail_url)
with open('某宝.csv', mode='a', encoding='utf-8', newline='') as f: csv_write = csv.writer(f) csv_write.writerow([info, price, deal, name, location, detail_url])
找到页面的规律,为一个等差数列,而第一页为0
for page in range(100): # 012 print(f'\n==================正在抓取第{page + 1}页数据====================') url = f'https://s.taobao.com/search?q=%E5%B7%B4%E9%BB%8E%E4%B8%96%E5%AE%B6&s={page * 44}' # 解析商品数据 parse_data() time.sleep(random.randint(1, 3)) # 尽量避免人机检测 随机延迟