天天看点

用selenium爬取淘宝美食

这里用淘宝来练习一下 selenium 的使用,可以替换关键字,爬取不同的物品,比如说衣服、鞋子之类的。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from pyquery import PyQuery as pq
import re,pymongo

borwser = webdriver.Chrome()#声明浏览器
url = 'https://www.taobao.com/'
wait = WebDriverWait(borwser,10)#显示等待
key_word = '美食'
def search(key_word):
    try:
        borwser.get(url)
        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')))
        input.send_keys(key_word)
        submit.click()
        total = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-pager>div>div>div>div.total')))
        get_products()
        return total.text
    except TimeoutError:
        return search(key_word)
           

这一部分主要是一些配置的信息,打开淘宝,找到输入框,然后输入关键字确定,如果在规定的时间内没有响应,可能是网速太慢,我们用了递归调用再次执行代码就好了。

def next_page(number):
    #处理翻页的操作
    #页面最下方翻页地方输入页码的框出来没有
    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(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(number)))
    get_products()
           

这一部分是处理翻页的,代码注释已经很详细了,不再过多啰嗦。

def get_products():
    #解析详情列表
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#mainsrp-itemlist .items .item')))#看看页面加载出来没有
    html = borwser.page_source#得到网页的源代码
    doc = pq(html)#用pq解析网页源代码
    #得到所有选中的内容
    items = doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        products = {
            'image': item.find('.pic .img').attr('data-src'),
            'price': item.find('.price').text()[3:],
            'deal': item.find('.deal-cnt').text(),
            'title': item.find('.title').text(),
            'shop': item.find('.shop').text(),
            'location': item.find('.location').text()
        }
        print(products)
        save_products(products)
           

这里是解析页面美食部分的代码,当然你的关键字是什么就解析什么,这里用到了 pyquery 这个库,你也可以使用其他的解析方法,比如说 xpath 、re 、bs4 等等

MONGO_URL = 'localhost'#本地数据库
MONGO_DB = 'taobaomeishi'#数据库名称
MONGO_TABLE = 'products'
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]

def save_products(result):
    try:
        if db[MONGO_TABLE].insert(result):
            print('保存MONGODB成功',result)
    except Exception:
        print('保存到MONGODB失败',result)



if __name__ == '__main__':
    total = search(key_word)
    total = int(re.findall('(\d+)',total)[0])
    for i in range(2,5):
        next_page(i)
           

觉得不错点个赞吧。

继续阅读