Python使用Selenium爬取淘宝异步加载的数据方法
作者:jingxian 发布时间:2021-05-17 05:31:57
标签:Python,Selenium,异步,加载
淘宝的页面很复杂,如果使用分析ajax或者js的方式,很麻烦
抓取淘宝‘美食'上面的所有食品信息
spider.py
#encoding:utf8
import re
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from config import *
import pymongo
client=pymongo.MongoClient(MONGODB_URL)
db=client[MONGODB_DB]
##这里使用PhantomJS,并配置了一些参数
browser=webdriver.PhantomJS(service_args=SERVICE_ArGS)
##窗口的大小,不设置的话,默认太小,会有问题
browser.set_window_size(1400,900)
wait=WebDriverWait(browser, 10)
def search():
print('正在搜索')
##容易出现超时的错误
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'))
)
######这块python2搞得鬼
#input.send_keys('\u7f8e\u98df'.decode("unicode-escape"))
input.send_keys(KEYWORD.decode("unicode-escape"))
submit.click()
total = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.total'))
)
get_product()
return total.text
except TimeoutException:
return search()
def next_page(page_number):
print('翻页'+str(page_number))
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_number)
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_number)))
get_product()
except TimeoutException:
return next_page(page_number)
#获取产品信息
def get_product():
products = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, '#mainsrp-itemlist .m-itemlist .items'))
)
##拿到网页
html = browser.page_source
soup = BeautifulSoup(html,'lxml')
items = soup.select('#mainsrp-itemlist .m-itemlist .items .item.J_MouserOnverReq')#
print('*************************到此*************')
for item in items:
img = item.select('.J_ItemPic.img')[0].get('src')
price = item.select('.price.g_price.g_price-highlight > strong')[0].get_text()
deal = item.select('.deal-cnt')[0].get_text()
title= item.select('.row.row-2.title > a ')[0].get_text().strip() #:nth-of-type(3)
shop = item.select('.row.row-3.g-clearfix > .shop > a > span:nth-of-type(2)')[0].get_text()
location = item.select('.location')[0].get_text()
product={
'img':img,
'price':price,
'deal':deal,
'title':title,
'shop':shop,
'location':location
}
#打印一下
import json
j = json.dumps(product)
dict2 = j.decode("unicode-escape")
print dict2
save_to_mongo(product)
def save_to_mongo(product):
try:
if db[MONGODB_TABLE].insert(product):
print('存储到mongodb成功'+str(product))
except Exception:
print("存储到mongodb失败"+str(product))
def main():
try:
total=search()
##搜寻 re正则表达式
s=re.compile('(\d+)')
total=int(s.search(total).group(1))
for i in range(2,total+1):
next_page(i)
except Exception:
print('出错')
finally:
browser.close()
if __name__ == '__main__':
main()
config.py
MONGODB_URL='localhost'
MONGODB_DB='taobao'
MONGODB_TABLE='meishi'
SERVICE_ArGS=['--load-images=false','--disk-cache=true']
##就是美食这两个字,直接用汉字会报错
KEYWORD='\u7f8e\u98df'
来源:https://blog.csdn.net/wqh_jingsong/article/details/66472106
0
投稿
猜你喜欢
- JavaScript中没有Trim函数,VBScript语言中才有这个函数,就是去掉字符串头和尾的空格。您可以访问这篇文章:《增加 java
- 使用SQLSERVER的应该经常遇到“Unable to read local eventlog (reason:事件日志文件已在读取时间更
- 问题一个已经有内容的 textarea 元素,在执行该元素的 .focus() 方法后,不同的浏览器有不同表现。我们的预期是能够出现在内容后
- PHP addAttribute() 函数实例给根元素和 body 元素添加一个属性:<?php $note=<<<
- 如果出现 automation服务器不能创建对象 解决方法:1、如果是Scripting.FileSystemObje
- 本文实例讲述了php中对象引用和复制。分享给大家供大家参考,具体如下:引用$tv2 = $tv1;或者$tv2 = &$tv1;以上
- 对于Dreamweaver这个广大用户早有听闻的网页编辑工具,除功能强大外,Dreamweaver一向被推崇为同类网页编辑软件中产生垃圾代码
- 多线程锁lock=threading.Lock()使用疑问多线程任务是同时执行的,如果我们需要先执行线程a,再执行线程b,需要怎么办呢?解决
- pipenv 是Kenneth Reitz大神的作品,能够有效管理Python多个环境,各种包。过去我们一般用virtualenv搭建虚拟环
- DOM遍历基于ID、元素类型、类名查找元素非常有用,但是如果你想基于它在DOM树中的位置来查找元素该怎么办?换句话说,你有一个给定的元素,你
- 本文实例讲述了php实现压缩多个CSS与JS文件的方法。分享给大家供大家参考。具体实现方法如下:1. 压缩css<?php
- 本文实例为大家分享了python策略模式代码,供大家参考,具体内容如下"""策略模式""&
- 前段时间冷空气突袭的时候,据说郊区密云的雪积得挺厚,但北京城内除了飘了一点小雪粒,毫无动静。应该是气温过高所致,我在慈云寺桥附近拍下的照片可
- 随机背景--当你每次进入该页面时,从已指定的图片文件夹中,随机选取一个图片作为背景显示。这里介绍的方法是用ASP+CSS来实现的。 &nbs
- 程序编制 随着WEB的发展,与浏览者的交互越来越受到网站制作者的重视。现在的主页跟最初的静态主
- python 中有6大标准类型:数字(Number)字符串(String)列表(List)元组(Tumple)集合(Set)字典(Dicti
- folder.htm<html><head><title>闪亮日子之在线创建文件夹</title&
- 阅读上一篇:交互设计模式(二)-Pagination(分页,标记页数) Tagging(标签)问题摘要用户往往想通过流行或最详尽的主题来浏览
- rss的优点 1.您可以有选择地浏览您感兴趣的以及与您的工作相关的新闻。 2.您可以把需要的信息从不需要的信息(兜售信息,垃圾邮件等)中分离
- 取余函数 PHP取余函数 PHP两个取余 MOD(x,y) x%yMOD例如:9/3,9是被除数,3为除数.mod函数是一个求余函数,其格式