问题如下:
我想爬取淘宝的商品信息,但是爬不到,希望老师能检查一下我的代码,希望老师不要敷衍,拜托了
zongzi.py
from selenium import webdriver
import time
import random
from cook import TAO_USERNAME, TAO_PASSWORD
import csv
def search_product(keyword):
"""根据关键字搜索商品,解决登录"""
# 输入关键字
driver.find_element_by_xpath('//*[@id="q"]').send_keys(keyword)
# 设置休息时间,随机休眠1—3秒钟
time.sleep(random.randint(1, 3))
# 点击搜索按钮
driver.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()
# 解决登录
# 输入用户名
driver.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys(TAO_USERNAME)
# 设置休息时间,随机休眠1—2秒钟
time.sleep(random.randint(1, 2))
# 输入密码
driver.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys(TAO_PASSWORD)
# 设置休息时间,随机休眠1—2秒钟
time.sleep(random.randint(1, 2))
# 点击登录按钮
driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click()
def parse_data():
"""解析数据"""
# 获取所有想要的div标签
divs = driver.find_elements_by_xpath('//div[@class="grid g-clearfix"]/div/div')
# 二次提取
for div in divs:
try:
title = 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').text # 详情页的URL
print(title, price, deal, name, location, detail_url)
# 保存文件
with open('淘宝.csv', mode='a', encoding='utf-8', newline='') as f:
csv_write = csv.writer(f) # 实例化csv模块写入对象
csv_write.writerow([title, price, deal, name, location, detail_url])
except:
continue
word = input('请输入你要搜索商品的关键字:')
# 创建一个浏览器
driver = webdriver.Chrome()
# 绕过selenium的检测
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",
{"source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"""})
# 执行自动化页面操作——输入要爬取得网站
driver.get('https://www.taobao.com/')
# 最大化窗口
driver.maximize_window()
# 设置浏览器的隐式等待
driver.implicitly_wait(10)
# 调用搜索商品的函数
search_product(word)
# 设置休息时间,随机休眠2-4秒钟
time.sleep(random.randint(2, 4))
# 获取前十页的数据
for page in range(100):
print(f'\n============================正在抓取第{page + 1}数据=====================================')
driver.get(f'https://www.taobao.com/search?a={word}&s={page * 44}')
# 调用数据解析函数
parse_data()
# 设置休息时间,随机休眠2-4秒钟
time.sleep(random.randint(2, 4))
cook.py
TAO_USERNAME = "用户"
TAO_PASSWORD = "密码"