文章目录
- python爬取京东网站自定义关键词商品信息(一)
- 1.新建文件夹workspace,在该目录下创建spdier.py文件
- 2.在spider.py文件中导入需要的库包,代码如下:
- 3.在workspace目录下创建config.py文件,编写代码如
- 4.配置mongodb数据库,代码如下:
- 5.主函数代码如下:
- 6.完成搜索函数,代码如下:
- 7.完成解析商品函数
- 8.完成页面解析函数以及保存到数据库
- 9.开启mongdb数据库:
- 10.这里我用的是robot3t,一款针对mongodb数据库可视化软件,可以直接打开连接本地数据库,完整代码:
- 11.运行spider.py文件,可以通过robot3t看见如图
python爬取京东网站自定义关键词商品信息(一)
1.新建文件夹workspace,在该目录下创建spdier.py文件
2.在spider.py文件中导入需要的库包,代码如下:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
import re,time
3.在workspace目录下创建config.py文件,编写代码如
MONGO_URL='localhost'
MONGO_DB='jd_goods'
MONG0_TABLE='jd_goods'
4.配置mongodb数据库,代码如下:
from config import MONGO_DB,MONG0_TABLE,MONGO_URL
from pymongo import MongoClient
client = MongoClient(MONGO_URL)
db=client[MONGO_DB]
5.主函数代码如下:
def main():
try:
chrome_options=Options()
chrome_options.add_argument("--headless")
browser=webdriver.Chrome(executable_path="C:\Python34\Scripts\chromedriver.exe",chrome_options=chrome_options)
browser = webdriver.Chrome()#创建谷歌浏览器对象
wait = WebDriverWait(browser, 10)#等待对象
browser.set_window_size(1400, 900)#设置浏览器页面大小
total = search()
total = int(re.compile('(\d+)').search(total).group(1))
for i in range(2, total + 1):
next_page(i)
except:
print("出错!")
finally:
browser.close()
if __name__=='__main__':
main()
6.完成搜索函数,代码如下:
def search():
try:
jd_url='https://www.jd.com/'
browser.get(jd_url)
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#key"))
)#固定用法,可参考selenium官方文档,获取到搜索输入框元素
submit=wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#search > div > div.form > button > i")))#获取到提交按钮元素
input.send_keys("美食")#固定用法
submit.click()#完成按钮点击
scroll_to_down()#控制鼠标下滑,完成页面数据全部显示出来
total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#J_bottomPage > span.p-skip > em:nth-child(1)"))).text#获取到页面底部关于页数的文本
get_product()#解析页面并完成存储到mongodb
return total#返回total文本信息
except TimeoutError:
return search()#由于selenium经常报出超时错误,如果出现就再次运行函数
def common_click(driver,element_id,sleeptime=2):#此处代码是网上百度的,完成页面点击操作
actions = ActionChains(driver)
actions.move_to_element(element_id)
actions.click(element_id)
actions.perform()
time.sleep(sleeptime)
def scroll_to_down(): #解决数据显示不全
browser.execute_script("window.scrollBy(0,3000)")
time.sleep(1)
browser.execute_script("window.scrollBy(0,5000)")
time.sleep(1)
browser.execute_script("window.scrollBy(0,8000)")
time.sleep(1)
7.完成解析商品函数
def next_page(page_num):
try:
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#J_bottomPage > span.p-skip > input"))
)
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_bottomPage > span.p-skip > a"))
)
input.clear()
input.send_keys(page_num)
submit.click()
scroll_to_down()
get_product()
wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,"#J_bottomPage > span.p-num > a.curr"),str(page_num)))#判断当前页面高亮
except TimeoutError:
return next_page(page_num)
8.完成页面解析函数以及保存到数据库
def get_product():
html=browser.page_source#获取到页面源码
response = etree.HTML(html.lower())#方便使用xpath解析页面
items = response.xpath('//li[@class="gl-item"]')#获取到商品所有项
for item in items:
try:
price = item.xpath('.//div[@class="p-price"]//strong//i/text()')[0]
shop = item.xpath('.//div[@class="p-shop"]//a/text()')[0]
src = item.xpath('.//div[@class="p-img"]//a//img/@src')[0]
eva_num = item.xpath('.//div[@class="p-commit"]//strong/a/text()')[0]
title = item.xpath('.//div[@class="p-name p-name-type-2"]//a/@title')[0]
product = {
'title': title,
'src': src,
'price': price,
'eva_num': eva_num,
'shop': shop,
}
# print(product)
save_to_mongo(product)#保存到数据库
except IndexError: #由于可能抛出数组越界,所以需要反馈异常,避免代码终止
pass
def save_to_mongo(dict):
if db[MONG0_TABLE].insert(dict):
print('存储到mongdb成功——————————')
return True
return False
9.开启mongdb数据库:
windows下win+r打开运行界面,输入cmd进入界面,输入:C:\Users\童>cd C:\Program Files\MongoDB\Server\3.4\bin
即mongodb安装路径bin文件夹下,然后输入:C:\Program Files\MongoDB\Server\3.4\bin>mongod -dbpath E:\mongodb\data\db
10.这里我用的是robot3t,一款针对mongodb数据库可视化软件,可以直接打开连接本地数据库,完整代码:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
import re,time
def search():
try:
jd_url='https://www.jd.com/'
browser.get(jd_url)
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#key"))
)#固定用法,可参考selenium官方文档,获取到搜索输入框元素
submit=wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#search > div > div.form > button > i")))#获取到提交按钮元素
input.send_keys("美食")#固定用法
submit.click()#完成按钮点击
scroll_to_down()#控制鼠标下滑,完成页面数据全部显示出来
total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#J_bottomPage > span.p-skip > em:nth-child(1)"))).text#获取到页面底部关于页数的文本
get_product()#解析页面并完成存储到mongodb
return total#返回total文本信息
except TimeoutError:
return search()#由于selenium经常报出超时错误,如果出现就再次运行函数
def common_click(driver,element_id,sleeptime=2):#此处代码是网上百度的,完成页面点击操作
actions = ActionChains(driver)
actions.move_to_element(element_id)
actions.click(element_id)
actions.perform()
time.sleep(sleeptime)
def scroll_to_down(): #解决数据显示不全
browser.execute_script("window.scrollBy(0,3000)")
time.sleep(1)
browser.execute_script("window.scrollBy(0,5000)")
time.sleep(1)
browser.execute_script("window.scrollBy(0,8000)")
time.sleep(1)
def next_page(page_num):
try:
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#J_bottomPage > span.p-skip > input"))
)
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "#J_bottomPage > span.p-skip > a"))
)
input.clear()
input.send_keys(page_num)
submit.click()
scroll_to_down()
get_product()
wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,"#J_bottomPage > span.p-num > a.curr"),str(page_num)))#判断当前页面高亮
except TimeoutError:
return next_page(page_num)
def get_product():
html=browser.page_source#获取到页面源码
response = etree.HTML(html.lower())#方便使用xpath解析页面
items = response.xpath('//li[@class="gl-item"]')#获取到商品所有项
for item in items:
try:
price = item.xpath('.//div[@class="p-price"]//strong//i/text()')[0]
shop = item.xpath('.//div[@class="p-shop"]//a/text()')[0]
src = item.xpath('.//div[@class="p-img"]//a//img/@src')[0]
eva_num = item.xpath('.//div[@class="p-commit"]//strong/a/text()')[0]
title = item.xpath('.//div[@class="p-name p-name-type-2"]//a/@title')[0]
product = {
'title': title,
'src': src,
'price': price,
'eva_num': eva_num,
'shop': shop,
}
# print(product)
save_to_mongo(product)#保存到数据库
except IndexError: #由于可能抛出数组越界,所以需要反馈异常,避免代码终止
pass
def save_to_mongo(dict):
if db[MONG0_TABLE].insert(dict):
print('存储到mongdb成功——————————')
return True
return False
def main():
try:
chrome_options=Options()#浏览器操作
chrome_options.add_argument("--headless")#设置无头浏览器
browser=webdriver.Chrome(executable_path="C:\Python34\Scripts\chromedriver.exe",chrome_options=chrome_options) #传递参数
browser = webdriver.Chrome()#创建谷歌浏览器对象
wait = WebDriverWait(browser, 10)#等待对象
browser.set_window_size(1400, 900)#设置浏览器页面大小
total = search()
total = int(re.compile('(\d+)').search(total).group(1))
for i in range(2, total + 1):
next_page(i)
except:
print("出错!")
finally:
browser.close()
if __name__=='__main__':
main()
11.运行spider.py文件,可以通过robot3t看见如图
可以看到数据库名为jd_goods下面生成一张同名的数据表