数据分析与数据挖掘 笔记2 京东搜索笔记本读取图片和价格等信息并保存到csv 作业存档,感谢大佬的指导
from selenium import webdriver
import time
import requests
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import os
try:
os.mkdir('img')
os.mkdir('data')
except FileExistsError:
print('已经有文件了,不需要创建~继续执行~')
driver = webdriver.Chrome(executable_path=r'D:\lession\demo\demo\chromedriver.exe')
driver.get('https://www.jd.com')
time.sleep(2)
driver.find_element_by_xpath('/html/body/div[1]/div[4]/div/div[2]/div/div[2]/input').send_keys('笔记本')
action = ActionChains(driver)
action.send_keys(Keys.ENTER).perform()
time.sleep(1)
height = 0
for i in range(1, 14):
js = 'var q=document.documentElement.scrollTop=%s' % height
height += 800
driver.execute_script(js)
time.sleep(1.5)
textHtml = driver.page_source
def add_csv(content, price):
"""
:param price: 价格
:param content: 主要写入的内容 这里写的是url地址
:return: 无返回
"""
with open('data/data.csv', 'a+') as csv:
try:
csv.write(content + "," + price + "\n")
except TypeError:
print('价格未获取到。')
def download_img(url, number):
"""
:param url: 下载图片的地址
:param number: 下载图片的序号 编号主要为了不重复名字
:return: 无返回
"""
content = requests.get(url).content
with open(f'img/{number}.jpg', 'wb+') as f:
f.write(content)
if __name__ == '__main__':
for i in range(59):
try:
img_url = driver.find_element_by_xpath(f'//*[@id="J_goodsList"]/ul/li[{i + 2}]/div/div[1]/a/img').get_attribute(
'src')
price = driver.find_element_by_xpath(f'//*[@id="J_goodsList"]/ul/li[{i + 2}]/div/div[2]/strong/i').text
print(img_url)
print(price)
add_csv(img_url, price)
download_img(img_url, i + 1)
print(f'下载成功文件为{i + 1}.jpg')
except FileNotFoundError:
print('文件路径不对,如果此路径下没有img文件夹请新建。')
break
except requests.exceptions.MissingSchema:
print('下载失败')
driver.close()
csv怎么添加标题???
|